home *** CD-ROM | disk | FTP | other *** search
/ Chip 2004 July / CMCD0704.ISO / Software / Freeware / Comunicatii / htttrack / httrack-3.32-2.exe / {app} / src / htslib.c < prev    next >
Encoding:
C/C++ Source or Header  |  2004-05-08  |  133.5 KB  |  4,920 lines

  1. /* ------------------------------------------------------------ */
  2. /*
  3. HTTrack Website Copier, Offline Browser for Windows and Unix
  4. Copyright (C) Xavier Roche and other contributors
  5.  
  6. This program is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU General Public License
  8. as published by the Free Software Foundation; either version 2
  9. of the License, or any later version.
  10.  
  11. This program is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with this program; if not, write to the Free Software
  18. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  19.  
  20.  
  21. Important notes:
  22.  
  23. - We hereby ask people using this source NOT to use it in purpose of grabbing
  24. emails addresses, or collecting any other private information on persons.
  25. This would disgrace our work, and spoil the many hours we spent on it.
  26.  
  27.  
  28. Please visit our Website: http://www.httrack.com
  29. */
  30.  
  31.  
  32. /* ------------------------------------------------------------ */
  33. /* File: Subroutines                                            */
  34. /* Author: Xavier Roche                                         */
  35. /* ------------------------------------------------------------ */
  36.  
  37. /* Internal engine bytecode */
  38. #define HTS_INTERNAL_BYTECODE
  39.  
  40. // Fichier librairie .c
  41.  
  42. #include "htslib.h"
  43. #include "htsbauth.h"
  44.  
  45. /* specific definitions */
  46. #include "htsbase.h"
  47. #include "htsnet.h"
  48. #include "htsbauth.h"
  49. #include "htsthread.h"
  50. #include "htsnostatic.h"
  51. #include "htswrap.h"
  52. #include "htsmd5.h"
  53. #if HTS_WIN
  54. #include <direct.h>
  55. #else
  56. #ifdef HAVE_SYS_TYPES_H
  57. #include <sys/types.h>
  58. #endif
  59. #ifdef HAVE_SYS_STAT_H
  60. #include <sys/stat.h>
  61. #endif
  62. #ifdef HAVE_UNISTD_H
  63. #include <unistd.h>
  64. #endif
  65. #endif
  66. #include <string.h>
  67. #include <time.h>
  68. #include <sys/timeb.h>
  69. #include <fcntl.h>
  70. // pour utimbuf
  71. #if HTS_WIN
  72. #include <sys/utime.h>
  73. #else
  74. #include <utime.h>
  75. #endif
  76. #include <sys/stat.h>
  77. /* END specific definitions */
  78.  
  79.  
  80. // Debugging
  81. #if _HTS_WIDE
  82. FILE* DEBUG_fp=NULL;
  83. #endif
  84.  
  85. /* variables globales */
  86. int _DEBUG_HEAD;
  87. FILE* ioinfo;
  88.  
  89. #if HTS_USEOPENSSL
  90.  SSL_CTX *openssl_ctx = NULL;
  91. #endif
  92. int IPV6_resolver = 0;
  93.  
  94.  
  95. /* dΘtection complΘmentaire */
  96. const char* hts_detect[] = {
  97.   "archive",
  98.   "background",
  99.   "data",         // OBJECT
  100.   "dynsrc",
  101.   "lowsrc",
  102.   "profile",      // element META
  103.   "src",
  104.   "swurl",
  105.   "url",
  106.   "usemap",
  107.   "longdesc",     // accessibility
  108.   "xlink:href",   // xml/svg tag
  109.   ""
  110. };
  111.  
  112. /* dΘtecter dΘbut */
  113. const char* hts_detectbeg[] = {
  114.   "hotspot",      /* hotspot1=..,hotspot2=.. */
  115.   ""
  116. };
  117.  
  118. /* ne pas dΘtcter de liens dedans */
  119. const char* hts_nodetect[] = {
  120.   "accept-charset",
  121.   "accesskey",
  122.   "action",
  123.   "align",
  124.   "alt",
  125.   "axes",
  126.   "axis",
  127.   "char",
  128.   "charset",
  129.   "cite",
  130.   "class",
  131.   "classid",
  132.   "code",
  133.   "color",
  134.   "datetime",
  135.   "dir",
  136.   "enctype",
  137.   "face",
  138.   "height",
  139.   "id",
  140.   "lang",
  141.   "language",
  142.   "media",
  143.   "method",
  144.   "name",
  145.   "prompt",
  146.   "scheme",
  147.   "size",
  148.   "style",
  149.   "target",
  150.   "title",
  151.   "type",
  152.   "valign",
  153.   "version",
  154.   "width",
  155.   ""
  156. };
  157.  
  158.  
  159. /* dΘtection de mini-code javascript */
  160. /* ALSO USED: detection based on the name: onXXX="<tag>" where XXX starts with upper case letter */
  161. const char* hts_detect_js[] = {
  162.   "onAbort",
  163.   "onBlur",
  164.   "onChange",
  165.   "onClick",
  166.   "onDblClick",
  167.   "onDragDrop",
  168.   "onError",
  169.   "onFocus",
  170.   "onKeyDown",
  171.   "onKeyPress",
  172.   "onKeyUp",
  173.   "onLoad",
  174.   "onMouseDown",
  175.   "onMouseMove",
  176.   "onMouseOut",
  177.   "onMouseOver",
  178.   "onMouseUp",
  179.   "onMove",
  180.   "onReset",
  181.   "onResize",
  182.   "onSelect",
  183.   "onSubmit",
  184.   "onUnload",
  185.   "style",          /* hack for CSS code data */
  186.   ""
  187. };
  188.  
  189. const char* hts_main_mime[] = {
  190.   "application",
  191.   "audio",
  192.   "image",
  193.   "message",
  194.   "multipart",
  195.   "text",
  196.   "video",
  197.   ""
  198. };
  199.  
  200. /* dΘtection "...URL=<url>" */
  201. const char* hts_detectURL[] = {
  202.   "content",
  203.   ""
  204. };
  205.  
  206. /* tags o∙ l'URL doit Ωtre rΘΘcrite mais non capturΘe */
  207. const char* hts_detectandleave[] = {
  208.   "action",
  209.   ""
  210. };
  211.  
  212. /* ne pas renommer les types renvoyΘs (souvent types inconnus) */
  213. const char* hts_mime_keep[] = {
  214.   "application/octet-stream",
  215.   "text/plain",
  216.   ""
  217. };
  218.  
  219. /* pas de type mime connu, mais extension connue */
  220. const char* hts_ext_dynamic[] = {
  221.   "php3",
  222.   "php",
  223.   "php4",
  224.   "php2",
  225.   "cgi",
  226.   "asp",
  227.   "jsp",
  228.   "pl",
  229.   /*"exe",*/
  230.   "cfm",
  231.   "nsf", /* lotus */
  232.   ""
  233. };
  234.  
  235. /* types MIME 
  236.    note: application/octet-stream should not be used here
  237. */
  238. const char* hts_mime[][2] = {
  239.   {"application/acad","dwg"},
  240.   {"application/arj","arj"},
  241.   {"application/clariscad","ccad"},
  242.   {"application/drafting","drw"},
  243.   {"application/dxf","dxf"},
  244.   {"application/excel","xls"},
  245.   {"application/i-deas","unv"},
  246.   {"application/iges","isg"},
  247.   {"application/iges","iges"},
  248.   {"application/mac-binhex40","hqx"},
  249.   {"application/mac-compactpro","cpt"},
  250.   {"application/msword","doc"},
  251.   {"application/msword","w6w"},
  252.   {"application/msword","word"},
  253.   {"application/mswrite","wri"},
  254.   /*{"application/octet-stream","dms"},*/
  255.   /*{"application/octet-stream","lzh"},*/
  256.   /*{"application/octet-stream","lha"},*/
  257.   /*{"application/octet-stream","bin"},*/
  258.   {"application/oda","oda"},
  259.   {"application/pdf","pdf"},
  260.   {"application/postscript","ps"},
  261.   {"application/postscript","ai"},
  262.   {"application/postscript","eps"},
  263.   {"application/powerpoint","ppt"},
  264.   {"application/pro_eng","prt"},
  265.   {"application/pro_eng","part"},
  266.   {"application/rtf","rtf"},
  267.   {"application/set","set"},
  268.   {"application/sla","stl"},
  269.   {"application/smil","smi"},
  270.   {"application/smil","smil"},
  271.   {"application/smil","sml"},
  272.   {"application/solids","sol"},
  273.   {"application/STEP","stp"},
  274.   {"application/STEP","step"},
  275.   {"application/vda","vda"},
  276.   {"application/x-authorware-map","aam"},     
  277.   {"application/x-authorware-seg","aas"},
  278.   {"application/x-authorware-bin","aab"},
  279.   {"application/x-cocoa","cco"},
  280.   {"application/x-csh","csh"},
  281.   {"application/x-director","dir"},
  282.   {"application/x-director","dcr"},
  283.   {"application/x-director","dxr"},
  284.   {"application/x-mif","mif"},
  285.   {"application/x-dvi","dvi"},
  286.   {"application/x-gzip","gz"},
  287.   {"application/x-gzip","gzip"},
  288.   {"application/x-hdf","hdf"},
  289.   {"application/x-javascript","js"},
  290.   {"application/x-koan","skp"},
  291.   {"application/x-koan","skd"},
  292.   {"application/x-koan","skt"},
  293.   {"application/x-koan","skm"},
  294.   {"application/x-latex","latex"},
  295.   {"application/x-netcdf","nc"},
  296.   {"application/x-netcdf","cdf"},
  297.   /* {"application/x-sh","sh"}, */
  298.   /* {"application/x-csh","csh"}, */
  299.   /* {"application/x-ksh","ksh"}, */
  300.   {"application/x-shar","shar"},
  301.   {"application/x-stuffit","sit"},
  302.   {"application/x-tcl","tcl"},
  303.   {"application/x-tex","tex"},
  304.   {"application/x-texinfo","texinfo"},
  305.   {"application/x-texinfo","texi"},
  306.   {"application/x-troff","t"},
  307.   {"application/x-troff","tr"},
  308.   {"application/x-troff","roff"},
  309.   {"application/x-troff-man","man"},
  310.   {"application/x-troff-me","ms"},
  311.   {"application/x-wais-source","src"},
  312.   {"application/zip","zip"},
  313.   {"application/x-zip-compressed","zip"},
  314.   {"application/x-bcpio","bcpio"},
  315.   {"application/x-cdlink","vcd"},
  316.   {"application/x-cpio","cpio"},
  317.   {"application/x-gtar","tgz"},
  318.   {"application/x-gtar","gtar"},
  319.   {"application/x-shar","shar"},
  320.   {"application/x-shockwave-flash","swf"},
  321.   {"application/x-sv4cpio","sv4cpio"},
  322.   {"application/x-sv4crc","sv4crc"},
  323.   {"application/x-tar","tar"},
  324.   {"application/x-ustar","ustar"},
  325.   {"application/x-winhelp","hlp"},
  326.   {"audio/midi","mid"},
  327.   {"audio/midi","midi"},
  328.   {"audio/midi","kar"},
  329.   {"audio/mpeg","mp3"},
  330.   {"audio/mpeg","mpga"},
  331.   {"audio/mpeg","mp2"},
  332.   {"audio/basic","au"},
  333.   {"audio/basic","snd"},
  334.   {"audio/x-aiff","aif"},
  335.   {"audio/x-aiff","aiff"},
  336.   {"audio/x-aiff","aifc"},
  337.   {"audio/x-pn-realaudio","rm"},
  338.   {"audio/x-pn-realaudio","ram"},
  339.   {"audio/x-pn-realaudio","ra"},
  340.   {"audio/x-pn-realaudio-plugin","rpm"},
  341.   {"audio/x-wav","wav"},
  342.   {"chemical/x-pdb","pdb"},
  343.   {"chemical/x-pdb","xyz"},
  344.   {"drawing/x-dwf","dwf"},
  345.   {"image/gif","gif"},
  346.   {"image/ief","ief"},
  347.   {"image/jpeg","jpg"},
  348.   {"image/jpeg","jpe"},
  349.   {"image/jpeg","jpeg"},
  350.   {"image/pict","pict"},
  351.   {"image/png","png"},
  352.   {"image/tiff","tiff"},
  353.   {"image/tiff","tif"},
  354.   {"image/svg+xml","svg"},
  355.   {"image/svg-xml","svg"},
  356.   {"image/x-cmu-raster","ras"},
  357.   {"image/x-freehand","fh4"},
  358.   {"image/x-freehand","fh7"},
  359.   {"image/x-freehand","fh5"},  
  360.   {"image/x-freehand","fhc"},
  361.   {"image/x-freehand","fh"},   
  362.   {"image/x-portable-anymap","pnm"},
  363.   {"image/x-portable-bitmap","pgm"},
  364.   {"image/x-portable-pixmap","ppm"},
  365.   {"image/x-rgb","rgb"},
  366.   {"image/x-xbitmap","xbm"},
  367.   {"image/x-xpixmap","xpm"},
  368.   {"image/x-xwindowdump","xwd"},
  369.   {"model/mesh","msh"},  
  370.   {"model/mesh","mesh"},  
  371.   {"model/mesh","silo"},  
  372.   {"multipart/x-zip","zip"},
  373.   {"multipart/x-gzip","gzip"},
  374.   {"text/css","css"},
  375.   {"text/html","html"},
  376.   {"text/html","htm"},
  377.   {"text/plain","txt"},
  378.   {"text/plain","g"},
  379.   {"text/plain","h"},
  380.   {"text/plain","c"},
  381.   {"text/plain","cc"},
  382.   {"text/plain","hh"},
  383.   {"text/plain","m"},
  384.   {"text/plain","f90"},
  385.   {"text/richtext","rtx"},
  386.   {"text/tab-separated-values","tsv"},
  387.   {"text/x-setext","etx"},
  388.   {"text/x-sgml","sgml"},
  389.   {"text/x-sgml","sgm"},
  390.   {"text/xml","xml"},  
  391.   {"text/xml","dtd"},  
  392.   {"video/mpeg","mpeg"},
  393.   {"video/mpeg","mpg"},
  394.   {"video/mpeg","mpe"},
  395.   {"video/quicktime","qt"},
  396.   {"video/quicktime","mov"},
  397.   {"video/x-msvideo","avi"},
  398.   {"video/x-sgi-movie","movie"},
  399.   {"x-conference/x-cooltalk","ice"},
  400.   /*{"application/x-httpd-cgi","cgi"},*/
  401.   {"x-world/x-vrml","wrl"},
  402.  
  403.   /* More from w3schools.com */
  404.   { "application/envoy", "evy" },
  405.   { "application/fractals", "fif" },
  406.   { "application/futuresplash", "spl" },
  407.   { "application/hta", "hta" },
  408.   { "application/internet-property-stream", "acx" },
  409.   { "application/msword", "dot" },
  410.   { "application/olescript", "axs" },
  411.   { "application/pics-rules", "prf" },
  412.   { "application/pkcs10", "p10" },
  413.   { "application/pkix-crl", "crl" },
  414.   { "application/set-payment-initiation", "setpay" },
  415.   { "application/set-registration-initiation", "setreg" },
  416.   { "application/vnd.ms-excel", "xla" },
  417.   { "application/vnd.ms-excel", "xlc" },
  418.   { "application/vnd.ms-excel", "xlm" },
  419.   { "application/vnd.ms-excel", "xls" },
  420.   { "application/vnd.ms-excel", "xlt" },
  421.   { "application/vnd.ms-excel", "xlw" },
  422.   { "application/vnd.ms-pkicertstore", "sst" },
  423.   { "application/vnd.ms-pkiseccat", "cat" },
  424.   { "application/vnd.ms-powerpoint", "pot" },
  425.   { "application/vnd.ms-powerpoint", "pps" },
  426.   { "application/vnd.ms-powerpoint", "ppt" },
  427.   { "application/vnd.ms-project", "mpp" },
  428.   { "application/vnd.ms-works", "wcm" },
  429.   { "application/vnd.ms-works", "wdb" },
  430.   { "application/vnd.ms-works", "wks" },
  431.   { "application/vnd.ms-works", "wps" },
  432.   { "application/x-compress", "z" },
  433.   { "application/x-compressed", "tgz" },
  434.   { "application/x-internet-signup", "ins" },
  435.   { "application/x-internet-signup", "isp" },
  436.   { "application/x-iphone", "iii" },
  437.   { "application/x-javascript", "js" },
  438.   { "application/x-msaccess", "mdb" },
  439.   { "application/x-mscardfile", "crd" },
  440.   { "application/x-msclip", "clp" },
  441.   { "application/x-msmediaview", "m13" },
  442.   { "application/x-msmediaview", "m14" },
  443.   { "application/x-msmediaview", "mvb" },
  444.   { "application/x-msmetafile", "wmf" },
  445.   { "application/x-msmoney", "mny" },
  446.   { "application/x-mspublisher", "pub" },
  447.   { "application/x-msschedule", "scd" },
  448.   { "application/x-msterminal", "trm" },
  449.   { "application/x-perfmon", "pma" },
  450.   { "application/x-perfmon", "pmc" },
  451.   { "application/x-perfmon", "pml" },
  452.   { "application/x-perfmon", "pmr" },
  453.   { "application/x-perfmon", "pmw" },
  454.   { "application/x-pkcs12", "p12" },
  455.   { "application/x-pkcs12", "pfx" },
  456.   { "application/x-pkcs7-certificates", "p7b" },
  457.   { "application/x-pkcs7-certificates", "spc" },
  458.   { "application/x-pkcs7-certreqresp", "p7r" },
  459.   { "application/x-pkcs7-mime", "p7c" },
  460.   { "application/x-pkcs7-mime", "p7m" },
  461.   { "application/x-pkcs7-signature", "p7s" },
  462.   { "application/x-troff-me", "me" },
  463.   { "application/x-x509-ca-cert", "cer" },
  464.   { "application/x-x509-ca-cert", "crt" },
  465.   { "application/x-x509-ca-cert", "der" },
  466.   { "application/ynd.ms-pkipko", "pko" },
  467.   { "audio/mid", "mid" },
  468.   { "audio/mid", "rmi" },
  469.   { "audio/mpeg", "mp3" },
  470.   { "audio/x-mpegurl", "m3u" },
  471.   { "image/bmp", "bmp" },
  472.   { "image/cis-cod", "cod" },
  473.   { "image/pipeg", "jfif" },
  474.   { "image/x-cmx", "cmx" },
  475.   { "image/x-icon", "ico" },
  476.   { "image/x-portable-bitmap", "pbm" },
  477.   { "message/rfc822", "mht" },
  478.   { "message/rfc822", "mhtml" },
  479.   { "message/rfc822", "nws" },
  480.   { "text/css", "css" },
  481.   { "text/h323", "323" },
  482.   { "text/html", "stm" },
  483.   { "text/iuls", "uls" },
  484.   { "text/plain", "bas" },
  485.   { "text/scriptlet", "sct" },
  486.   { "text/webviewhtml", "htt" },
  487.   { "text/x-component", "htc" },
  488.   { "text/x-vcard", "vcf" },
  489.   { "video/mpeg", "mp2" },
  490.   { "video/mpeg", "mpa" },
  491.   { "video/mpeg", "mpv2" },
  492.   { "video/x-la-asf", "lsf" },
  493.   { "video/x-la-asf", "lsx" },
  494.   { "video/x-ms-asf", "asf" },
  495.   { "video/x-ms-asf", "asr" },
  496.   { "video/x-ms-asf", "asx" },
  497.   { "x-world/x-vrml", "flr" },
  498.   { "x-world/x-vrml", "vrml" },
  499.   { "x-world/x-vrml", "wrz" },
  500.   { "x-world/x-vrml", "xaf" },
  501.   { "x-world/x-vrml", "xof" },
  502.  
  503.   /* Various */
  504.   { "application/ogg", "ogg" },
  505.  
  506.   {"*","class"},
  507.   
  508.   {"",""}};
  509.  
  510.  
  511. // Reserved (RFC2396)
  512. #define CIS(c,ch) ( ((unsigned char)(c)) == (ch) )
  513. #define CHAR_RESERVED(c)  ( CIS(c,';') \
  514.                          || CIS(c,'/') \
  515.                          || CIS(c,'?') \
  516.                          || CIS(c,':') \
  517.                          || CIS(c,'@') \
  518.                          || CIS(c,'&') \
  519.                          || CIS(c,'=') \
  520.                          || CIS(c,'+') \
  521.                          || CIS(c,'$') \
  522.                          || CIS(c,',') )
  523. //#define CHAR_RESERVED(c)  ( strchr(";/?:@&=+$,",(unsigned char)(c)) != 0 )
  524. // Delimiters (RFC2396)
  525. #define CHAR_DELIM(c)     ( CIS(c,'<') \
  526.                          || CIS(c,'>') \
  527.                          || CIS(c,'#') \
  528.                          || CIS(c,'%') \
  529.                          || CIS(c,'\"') )
  530. //#define CHAR_DELIM(c)     ( strchr("<>#%\"",(unsigned char)(c)) != 0 )
  531. // Unwise (RFC2396)
  532. #define CHAR_UNWISE(c)    ( CIS(c,'{') \
  533.                          || CIS(c,'}') \
  534.                          || CIS(c,'|') \
  535.                          || CIS(c,'\\') \
  536.                          || CIS(c,'^') \
  537.                          || CIS(c,'[') \
  538.                          || CIS(c,']') \
  539.                          || CIS(c,'`') )
  540. //#define CHAR_UNWISE(c)    ( strchr("{}|\\^[]`",(unsigned char)(c)) != 0 )
  541. // Special (escape chars) (RFC2396 + >127 )
  542. #define CHAR_LOW(c)       ( ((unsigned char)(c) <= 31) )
  543. #define CHAR_HIG(c)       ( ((unsigned char)(c) >= 127) )
  544. #define CHAR_SPECIAL(c)   ( CHAR_LOW(c) || CHAR_HIG(c) )
  545. // We try to avoid them and encode them instead
  546. #define CHAR_XXAVOID(c)   ( CIS(c,' ') \
  547.                          || CIS(c,'*') \
  548.                          || CIS(c,'\'') \
  549.                          || CIS(c,'\"') \
  550.                          || CIS(c,'!') )
  551. //#define CHAR_XXAVOID(c)   ( strchr(" *'\"!",(unsigned char)(c)) != 0 )
  552. #define CHAR_MARK(c)      ( CIS(c,'-') \
  553.                          || CIS(c,'_') \
  554.                          || CIS(c,'.') \
  555.                          || CIS(c,'!') \
  556.                          || CIS(c,'~') \
  557.                          || CIS(c,'*') \
  558.                          || CIS(c,'\'') \
  559.                          || CIS(c,'(') \
  560.                          || CIS(c,')') )
  561. //#define CHAR_MARK(c)      ( strchr("-_.!~*'()",(unsigned char)(c)) != 0 )
  562.  
  563.  
  564.  
  565. // conversion Θventuelle / vers antislash
  566. #if HTS_WIN
  567. char* antislash(char* s) {
  568.   char* buff;
  569.   char* a;
  570.   NOSTATIC_RESERVE(buff, char, HTS_URLMAXSIZE*2);
  571.  
  572.   strcpybuff(buff,s);
  573.   while(a=strchr(buff,'/')) *a='\\';
  574.   return buff;
  575. }
  576. #endif
  577.  
  578.  
  579.  
  580. // RΘcupΘration d'un fichier http sur le net.
  581. // Renvoie une adresse sur le bloc de mΘmoire, ou bien
  582. // NULL si un retour.msgeur (buffer retour.msg) est survenue. 
  583. //
  584. // Une adresse de structure htsmsg peut Ωtre transmise pour
  585. // suivre l'Θvolution du chargement si le process a ΘtΘ lancΘ 
  586. // en background
  587.  
  588. htsblk httpget(char* url) {
  589.   char adr[HTS_URLMAXSIZE*2];   // adresse
  590.   char fil[HTS_URLMAXSIZE*2];   // chemin
  591.   
  592.   // sΘparer URL en adresse+chemin
  593.   if (ident_url_absolute(url,adr,fil)==-1) {
  594.     htsblk retour;
  595.     memset(&retour, 0, sizeof(htsblk));    // effacer
  596.     // retour prΘdΘfini: erreur
  597.     retour.adr=NULL;
  598.     retour.size=0;
  599.     retour.msg[0]='\0';
  600.     retour.statuscode=-1;    
  601.     strcpybuff(retour.msg,"Error invalid URL");
  602.     return retour;
  603.   }
  604.   
  605.   return xhttpget(adr,fil);
  606. }
  607.  
  608. // ouvre une liaison http, envoie une requΦte GET et rΘceptionne le header
  609. // retour: socket
  610. int http_fopen(char* adr,char* fil,htsblk* retour) {
  611.   //                / GET, traiter en-tΩte
  612.   return http_xfopen(0,1,1,NULL,adr,fil,retour);
  613. }
  614.  
  615. // ouverture d'une liaison http, envoi d'une requΦte
  616. // mode: 0 GET  1 HEAD  [2 POST]
  617. // treat: traiter header?
  618. // waitconnect: attendre le connect()
  619. // note: dans retour, on met les params du proxy
  620. int http_xfopen(int mode,int treat,int waitconnect,char* xsend,char* adr,char* fil,htsblk* retour) {
  621.   //htsblk retour;
  622.   //int bufl=TAILLE_BUFFER;    // 8Ko de buffer
  623.   T_SOC soc=INVALID_SOCKET;
  624.   //char *p,*q;
  625.   
  626.   // retour prΘdΘfini: erreur
  627.   if (retour) {
  628.     retour->adr=NULL;
  629.     retour->size=0;
  630.     retour->msg[0]='\0';
  631.     retour->statuscode=-5;          // a priori erreur non fatale
  632.   }
  633.  
  634. #if HDEBUG
  635.   printf("adr=%s\nfichier=%s\n",adr,fil);
  636. #endif
  637.   
  638.   // ouvrir liaison
  639. #if HDEBUG
  640.   printf("CrΘation d'une socket sur %s\n",adr);
  641. #endif
  642.  
  643. #if CNXDEBUG
  644.   printf("..newhttp\n");
  645. #endif
  646.  
  647.   /* connexion */
  648.   if (retour) {
  649.     if ( (!(retour->req.proxy.active)) 
  650.       ||
  651.       (
  652.         (strcmp(adr,"file://")==0) 
  653.         ||
  654.         (strncmp(adr,"https://", 8)==0) 
  655.       )
  656.       ) {    /* pas de proxy, ou non utilisable ici */
  657.       soc=newhttp(adr,retour,-1,waitconnect);
  658.     } else {
  659.       soc=newhttp(retour->req.proxy.name,retour,retour->req.proxy.port,waitconnect);  // ouvrir sur le proxy α la place
  660.     }
  661.   } else {
  662.     soc=newhttp(adr,NULL,-1,waitconnect);    
  663.   }
  664.  
  665.   // copier index socket retour
  666.   if (retour) retour->soc=soc;
  667.  
  668.   /* Check for errors */
  669.   if (soc == INVALID_SOCKET) {
  670.     if (retour) {
  671.       if (retour->msg) {
  672.         if (!strnotempty(retour->msg)) {
  673.           strcpybuff(retour->msg,"Connect error");
  674.         }
  675.       }
  676.     }
  677.   }
  678.  
  679.   // --------------------
  680.   // court-circuit (court circuite aussi le proxy..)
  681.   // LOCAL_SOCKET_ID est une pseudo-socket locale
  682.   if (soc==LOCAL_SOCKET_ID) {
  683.     retour->is_file=1;  // fichier local
  684.     if (mode==0) {    // GET
  685.  
  686.       // Test en cas de file:///C|...
  687.       if (!fexist(fconv(unescape_http(fil))))
  688.         if (fexist(fconv(unescape_http(fil+1)))) {
  689.           char tempo[HTS_URLMAXSIZE*2];
  690.           strcpybuff(tempo,fil+1);
  691.           strcpybuff(fil,tempo);
  692.         }
  693.  
  694.       // Ouvrir
  695.       retour->totalsize=fsize(fconv(unescape_http(fil)));  // taille du fichier
  696.       retour->msg[0]='\0';
  697.       soc=INVALID_SOCKET;
  698.       if (retour->totalsize<0)
  699.         strcpybuff(retour->msg,"Unable to open local file");
  700.       else if (retour->totalsize==0)
  701.         strcpybuff(retour->msg,"File empty");
  702.       else {
  703.         // Note: On passe par un FILE* (plus propre)
  704.         //soc=open(fil,O_RDONLY,0);    // en lecture seule!
  705.         retour->fp=fopen(fconv(unescape_http(fil)),"rb");  // ouvrir
  706.         if (retour->fp==NULL)
  707.           soc=INVALID_SOCKET;
  708.         else
  709.           soc=LOCAL_SOCKET_ID;
  710.       }
  711.       retour->soc=soc;
  712.       if (soc!=INVALID_SOCKET) {
  713.         retour->statuscode=200;   // OK
  714.         strcpybuff(retour->msg,"OK");
  715.         guess_httptype(retour->contenttype,fil);
  716.       } else if (strnotempty(retour->msg)==0)
  717.           strcpybuff(retour->msg,"Unable to open local file");
  718.       return soc;  // renvoyer
  719.     } else {    // HEAD ou POST : interdit sur un local!!!! (c'est idiot!)
  720.       strcpybuff(retour->msg,"Unexpected Head/Post local request");
  721.       soc=INVALID_SOCKET;    // erreur
  722.       retour->soc=soc;
  723.       return soc;
  724.     }
  725.   } 
  726.   // --------------------
  727.  
  728.   if (soc!=INVALID_SOCKET) {    
  729.     char rcvd[1100];
  730.     rcvd[0]='\0';
  731. #if HDEBUG
  732.     printf("Ok, connexion rΘussie, id=%d\n",soc);
  733. #endif
  734.     
  735.     // connectΘ?
  736.     if (waitconnect) {
  737.       http_sendhead(NULL,mode,xsend,adr,fil,NULL,NULL,retour);
  738.     } 
  739.     
  740.     if (soc!=INVALID_SOCKET) {
  741.       
  742. #if HDEBUG
  743.       printf("Attente de la rΘponse:\n");
  744. #endif
  745.       
  746.       // si GET (rΘception d'un fichier), rΘceptionner en-tΩte d'abord,
  747.       // et ensuite le corps
  748.       // si POST on ne rΘceptionne rien du tout, c'est aprΦs que l'on fera
  749.       // une rΘception standard pour rΘcupΘrer l'en tΩte
  750.       if ((treat) && (waitconnect)) {  // traiter (attendre!) en-tΩte        
  751.         // RΘception de la status line et de l'en-tΩte (norme RFC1945)
  752.         
  753.         // status-line α rΘcupΘrer
  754.         finput(soc,rcvd,1024);
  755.         if (strnotempty(rcvd)==0)
  756.           finput(soc,rcvd,1024);    // "certains serveurs buggΘs envoient un \n au dΘbut" (RFC)
  757.  
  758.         // traiter status-line
  759.         treatfirstline(retour,rcvd);
  760.  
  761. #if HDEBUG
  762.         printf("Status-Code=%d\n",retour->statuscode);
  763. #endif
  764.         
  765.         // en-tΩte
  766.         
  767.         // header // ** !attention! HTTP/0.9 non supportΘ
  768.         do {
  769.           finput(soc,rcvd,1024);          
  770. #if HDEBUG
  771.           printf(">%s\n",rcvd);      
  772. #endif
  773.           if (strnotempty(rcvd))
  774.             treathead(NULL,NULL,NULL,retour,rcvd);  // traiter
  775.  
  776.         } while(strnotempty(rcvd));
  777.         
  778.         //rcvsize=-1;    // forCER CHARGEMENT INCONNU
  779.         
  780.         //if (retour)
  781.         //  retour->totalsize=rcvsize;
  782.         
  783.       } else { // si GET, on recevra l'en tΩte APRES
  784.         //rcvsize=-1;    // on ne connait pas la taille de l'en-tΩte
  785.         if (retour)
  786.           retour->totalsize=-1;
  787.       }
  788.       
  789.     }
  790.  
  791.   }
  792.     
  793.   return soc;
  794. }
  795.  
  796.  
  797. // envoi d'une requΦte
  798. int http_sendhead(t_cookie* cookie,int mode,char* xsend,char* adr,char* fil,char* referer_adr,char* referer_fil,htsblk* retour) {
  799.   char buff[8192];
  800.   //int use_11=0;     // HTTP 1.1 utilisΘ
  801.   int direct_url=0; // ne pas analyser l'url (exemple: ftp://)
  802.   char* search_tag=NULL;
  803.   buff[0]='\0';
  804.  
  805.   // header Date
  806.   //strcatbuff(buff,"Date: ");
  807.   //time_gmt_rfc822(buff);    // obtenir l'heure au format rfc822
  808.   //sendc("\n");
  809.   //strcatbuff(buff,buff);
  810.  
  811.   // possibilitΘ non documentΘe: >post: et >postfile:
  812.   // si prΘsence d'un tag >post: alors executer un POST
  813.   // exemple: http://www.someweb.com/test.cgi?foo>post:posteddata=10&foo=5
  814.   // si prΘsence d'un tag >postfile: alors envoyer en tΩte brut contenu dans le fichier en question
  815.   // exemple: http://www.someweb.com/test.cgi?foo>postfile:post0.txt
  816.   search_tag=strstr(fil,POSTTOK":");
  817.   if (!search_tag) {
  818.     search_tag=strstr(fil,POSTTOK"file:");
  819.     if (search_tag) {     // postfile
  820.       if (mode==0) {      // GET!
  821.         FILE* fp=fopen(unescape_http(search_tag+strlen(POSTTOK)+5),"rb");
  822.         if (fp) {
  823.           char line[1100];
  824.           char protocol[256],url[HTS_URLMAXSIZE*2],method[256];
  825.           linput(fp,line,1000);
  826.           if (sscanf(line,"%s %s %s",method,url,protocol) == 3) {
  827.             // selon que l'on a ou pas un proxy
  828.             if (retour->req.proxy.active)
  829.               sprintf(buff,"%s http://%s%s %s\r\n",method,adr,url,protocol);
  830.             else
  831.               sprintf(buff,"%s %s %s\r\n",method,url,protocol);
  832.             // lire le reste en brut
  833.             fread(buff+strlen(buff),8000-strlen(buff),1,fp);
  834.           }
  835.           fclose(fp);
  836.         }
  837.       }
  838.     }
  839.   }
  840.   // Fin postfile
  841.   
  842.   if (strnotempty(buff)==0) {    // PAS POSTFILE
  843.     // Type de requΦte?
  844.     if ((search_tag) && (mode==0)) {
  845.       strcatbuff(buff,"POST ");
  846.     } else if (mode==0) {    // GET
  847.       strcatbuff(buff,"GET ");
  848.     } else {  // if (mode==1) {
  849.       if (!retour->req.http11)        // forcer HTTP/1.0
  850.         strcatbuff(buff,"GET ");      // certains serveurs (cgi) buggent avec HEAD
  851.       else
  852.         strcatbuff(buff,"HEAD ");
  853.     }
  854.     
  855.     // si on gΦre un proxy, il faut une Absolute URI: on ajoute avant http://www.adr.dom
  856.     if ( retour->req.proxy.active && (strncmp(adr,"https://", 8) != 0) ) {
  857.       if (!link_has_authority(adr)) {  // default http
  858. #if HDEBUG
  859.         printf("Proxy Use: for %s%s proxy %d port %d\n",adr,fil,retour->req.proxy.name,retour->req.proxy.port);
  860. #endif
  861.         strcatbuff(buff,"http://");
  862.         strcatbuff(buff,jump_identification(adr));
  863.       } else {          // ftp:// en proxy http
  864. #if HDEBUG
  865.         printf("Proxy Use for ftp: for %s%s proxy %d port %d\n",adr,fil,retour->req.proxy.name,retour->req.proxy.port);
  866. #endif
  867.         direct_url=1;             // ne pas analyser user/pass
  868.         strcatbuff(buff,adr);
  869.       }
  870.     } 
  871.     
  872.     // NOM DU FICHIER
  873.     // on slash doit Ωtre prΘsent en dΘbut, sinon attention aux bad request! (400)
  874.     if (*fil!='/') strcatbuff(buff,"/");
  875.     {
  876.       char tempo[HTS_URLMAXSIZE*2];
  877.       tempo[0]='\0';
  878.       if (search_tag)
  879.         strncatbuff(tempo,fil,(int) (search_tag - fil));
  880.       else
  881.         strcpybuff(tempo,fil);
  882.       escape_check_url(tempo);
  883.       strcatbuff(buff,tempo);       // avec Θchappement
  884.     }
  885.     
  886.     // protocole
  887.     if (!retour->req.http11) {     // forcer HTTP/1.0
  888.       //use_11=0;
  889.       strcatbuff(buff," HTTP/1.0\x0d\x0a");
  890.     } else {                   // RequΦte 1.1
  891.       //use_11=1;
  892.       strcatbuff(buff," HTTP/1.1\x0d\x0a");
  893.     }
  894.  
  895.     /* supplemental data */
  896.     if (xsend) strcatbuff(buff,xsend);    // Θventuelles autres lignes
  897.  
  898.     // tester proxy authentication
  899.     if (retour->req.proxy.active) {
  900.       if (link_has_authorization(retour->req.proxy.name)) {  // et hop, authentification proxy!
  901.         char* a=jump_identification(retour->req.proxy.name);
  902.         char* astart=jump_protocol(retour->req.proxy.name);
  903.         char autorisation[1100];
  904.         char user_pass[256];        
  905.         autorisation[0]=user_pass[0]='\0';
  906.         //
  907.         strncatbuff(user_pass,astart,(int) (a - astart) - 1);
  908.         strcpybuff(user_pass,unescape_http(user_pass));
  909.         code64((unsigned char*)user_pass,(int)strlen(user_pass),(unsigned char*)autorisation,0);
  910.         strcatbuff(buff,"Proxy-Authorization: Basic ");
  911.         strcatbuff(buff,autorisation);
  912.         strcatbuff(buff,H_CRLF);
  913. #if HDEBUG
  914.         printf("Proxy-Authenticate, %s (code: %s)\n",user_pass,autorisation);
  915. #endif
  916.       }
  917.     }
  918.     
  919.     // Referer?
  920.     if (referer_adr != NULL && referer_fil != NULL 
  921.       && strnotempty(referer_adr) && strnotempty(referer_fil)
  922.       ) {   // non vide
  923.       if (
  924.         (strcmp(referer_adr,"file://") != 0)
  925.         &&
  926.         (  /* no https referer to http urls */
  927.         (strncmp(referer_adr, "https://", 8) != 0)  /* referer is not https */
  928.         ||
  929.         (strncmp(adr, "https://", 8) == 0)          /* or referer AND addresses are https */
  930.         )
  931.         ) {      // PAS file://
  932.         strcatbuff(buff,"Referer: ");
  933.         strcatbuff(buff,"http://");
  934.         strcatbuff(buff,jump_identification(referer_adr));
  935.         strcatbuff(buff,referer_fil);
  936.         strcatbuff(buff,H_CRLF);
  937.       }
  938.     }
  939.     // HTTP field: referer
  940.     else if (retour->req.referer[0] != '\0') {
  941.       strcatbuff(buff,"Referer: ");
  942.       strcatbuff(buff, retour->req.referer);
  943.       strcatbuff(buff, H_CRLF);     
  944.     }
  945.     
  946.     // POST?
  947.     if (mode==0) {      // GET!
  948.       if (search_tag) {
  949.         char clen[256];
  950.         sprintf(clen,"Content-length: %d"H_CRLF,(int)(strlen(unescape_http(search_tag+strlen(POSTTOK)+1))));
  951.         strcatbuff(buff,clen);
  952.       }
  953.     }
  954.     
  955.     // gestion cookies?
  956.     if (cookie) {
  957.       char* b=cookie->data;
  958.       int cook=0;
  959.       int max_cookies=8;
  960.       int max_size=2048;
  961.       max_size+=strlen(buff);
  962.       do {
  963.         b=cookie_find(b,"",jump_identification(adr),fil);       // prochain cookie satisfaisant aux conditions
  964.         if (b) {
  965.           max_cookies--;
  966.           if (!cook) {
  967.             strcatbuff(buff,"Cookie: ");
  968.             strcatbuff(buff,"$Version=1; ");
  969.             cook=1;
  970.           } else
  971.             strcatbuff(buff,"; ");
  972.           strcatbuff(buff,cookie_get(b,5));
  973.           strcatbuff(buff,"=");
  974.           strcatbuff(buff,cookie_get(b,6));
  975.           strcatbuff(buff,"; $Path=");
  976.           strcatbuff(buff,cookie_get(b,2));
  977.           b=cookie_nextfield(b);
  978.         }
  979.       } while( (b) && (max_cookies>0) && ((int)strlen(buff)<max_size));
  980.       if (cook) {                           // on a envoyΘ un (ou plusieurs) cookie?
  981.         strcatbuff(buff,H_CRLF);
  982. #if DEBUG_COOK
  983.         printf("Header:\n%s\n",buff);
  984. #endif
  985.       }
  986.     }
  987.     
  988.     // gΘrer le keep-alive (garder socket)
  989.     if (retour->req.http11 && !retour->req.nokeepalive) {
  990.             strcatbuff(buff,"Connection: Keep-Alive"H_CRLF);
  991.         } else {
  992.       strcatbuff(buff,"Connection: close"H_CRLF);
  993.         }
  994.     
  995.     {
  996.       char* real_adr=jump_identification(adr);
  997.       //if ((use_11) || (retour->user_agent_send)) {   // Pour le 1.1 on utilise un Host:
  998.       if (!direct_url) {     // pas ftp:// par exemple
  999.         //if (!retour->req.proxy.active) {
  1000.         strcatbuff(buff,"Host: "); strcatbuff(buff,real_adr); strcatbuff(buff,H_CRLF);
  1001.         //}
  1002.       }
  1003.       //}
  1004.  
  1005.       // HTTP field: from
  1006.       if (retour->req.from[0] != '\0') {  // HTTP from
  1007.         strcatbuff(buff,"From: ");
  1008.         strcatbuff(buff, retour->req.from);
  1009.         strcatbuff(buff, H_CRLF);
  1010.       }
  1011.  
  1012.       // PrΘsence d'un user-agent?
  1013.       if (retour->req.user_agent_send) {  // ohh un user-agent
  1014.         char s[256];
  1015.         // HyperTextSeeker/"HTSVERSION
  1016.         sprintf(s,"User-Agent: %s"H_CRLF,retour->req.user_agent);
  1017.         strcatbuff(buff,s);
  1018.         
  1019.         // pour les serveurs difficiles
  1020.         strcatbuff(buff,"Accept: "
  1021.                         "image/png, image/jpeg, image/pjpeg, image/x-xbitmap, image/svg+xml"  /* Accepted */
  1022.                         ", "
  1023.                         "image/gif;q=0.9"  /* also accepted but with lower preference */
  1024.                         ", "
  1025.                         "*/*;q=0.1"        /* also accepted but with even lower preference */
  1026.                         H_CRLF);
  1027.         if (strnotempty(retour->req.lang_iso)) {
  1028.           strcatbuff(buff,"Accept-Language: "); strcatbuff(buff,retour->req.lang_iso); strcatbuff(buff,H_CRLF);
  1029.         }
  1030.         strcatbuff(buff,"Accept-Charset: "
  1031.                         "iso-8859-1"       /* we prefer ISO-8859-1 */
  1032.                         ", "
  1033.                         "iso-8859-*;q=0.9" /* or ISO-8859-* */
  1034.                         ", "
  1035.                         "utf-8;q=0.66"     /* UTF8 is also accepted */
  1036.                         ", "
  1037.                         "*;q=0.33"         /* and any other charset */
  1038.                         H_CRLF);   
  1039.         if (retour->req.http11) {
  1040. #if HTS_USEZLIB
  1041.           //strcatbuff(buff,"Accept-Encoding: gzip, deflate, compress, identity"H_CRLF);
  1042.           if (gz_is_available && (!retour->req.range_used) && (!retour->req.nocompression))
  1043.             strcatbuff(buff,"Accept-Encoding: "
  1044.                             "gzip"         /* gzip if the preffered encoding */
  1045.                             ", "
  1046.                             "identity;q=0.9"
  1047.                             H_CRLF);
  1048.           else
  1049.             strcatbuff(buff,"Accept-Encoding: identity"H_CRLF);       /* no compression */
  1050. #else
  1051.           strcatbuff(buff,"Accept-Encoding: identity"H_CRLF);         /* no compression */
  1052. #endif
  1053.         }
  1054.       } else {
  1055.         strcatbuff(buff,"Accept: */*"H_CRLF);         // le minimum
  1056.       }
  1057.  
  1058.       /* Authentification */
  1059.       {
  1060.         char autorisation[1100];
  1061.         char* a;
  1062.         autorisation[0]='\0';
  1063.         if (link_has_authorization(adr)) {  // ohh une authentification!
  1064.           char* a=jump_identification(adr);
  1065.           char* astart=jump_protocol(adr);
  1066.           if (!direct_url) {      // pas ftp:// par exemple
  1067.             char user_pass[256];
  1068.             user_pass[0]='\0';
  1069.             strncatbuff(user_pass,astart,(int) (a - astart) - 1);
  1070.             strcpybuff(user_pass,unescape_http(user_pass));
  1071.             code64((unsigned char*)user_pass,(int)strlen(user_pass),(unsigned char*)autorisation,0);
  1072.             if (strcmp(fil,"/robots.txt"))      /* pas robots.txt */
  1073.               bauth_add(cookie,astart,fil,autorisation);
  1074.           }
  1075.         } else if ( (a=bauth_check(cookie,real_adr,fil)) )
  1076.           strcpybuff(autorisation,a);
  1077.         /* On a une autorisation a donner?  */
  1078.         if (strnotempty(autorisation)) {
  1079.           strcatbuff(buff,"Authorization: Basic ");
  1080.           strcatbuff(buff,autorisation);
  1081.           strcatbuff(buff,H_CRLF);
  1082.         }
  1083.       }
  1084.  
  1085.     }
  1086.     //strcatbuff(buff,"Accept-Language: en\n");
  1087.     //strcatbuff(buff,"Accept-Charset: iso-8859-1,*,utf-8\n");
  1088.     
  1089.     // CRLF de fin d'en tΩte
  1090.     strcatbuff(buff,H_CRLF);
  1091.     
  1092.     // donnΘes complΘmentaires?
  1093.     if (search_tag)
  1094.     if (mode==0)      // GET!
  1095.       strcatbuff(buff,unescape_http(search_tag+strlen(POSTTOK)+1));
  1096.   }
  1097.   
  1098. #if HDEBUG
  1099. #endif
  1100.   if (_DEBUG_HEAD) {
  1101.     if (ioinfo) {
  1102.       fprintf(ioinfo,"[%d] request for %s%s:\r\n",retour->debugid,jump_identification(adr),fil);
  1103.       fprintfio(ioinfo,buff,"<<< ");
  1104.       fprintf(ioinfo,"\r\n");
  1105.       fflush(ioinfo);
  1106.     }
  1107.   }  // Fin test pas postfile
  1108.   //
  1109.  
  1110.   // Callback
  1111. #if HTS_ANALYSTE
  1112.   if (hts_htmlcheck_sendhead != NULL) {
  1113.     int test_head=hts_htmlcheck_sendhead(buff, adr, fil, referer_adr, referer_fil, retour);
  1114.     if (test_head!=1) {
  1115.       deletesoc_r(retour);
  1116.       strcpybuff(retour->msg,"Header refused by external wrapper");
  1117.       retour->soc=INVALID_SOCKET;
  1118.     }
  1119.   }
  1120. #endif
  1121.  
  1122.   // Envoi
  1123.   if (sendc(retour, buff)<0) {  // ERREUR, socket rompue?...
  1124.   //if (sendc(retour->soc,buff) != strlen(buff)) {  // ERREUR, socket rompue?...
  1125.     deletesoc_r(retour);  // fermer tout de mΩme
  1126.     // et tenter de reconnecter
  1127.     
  1128.     strcpybuff(retour->msg,"Write error");
  1129.     retour->soc=INVALID_SOCKET;
  1130.   }
  1131.   
  1132.   // RX'98
  1133.   return 0;
  1134. }
  1135.  
  1136.  
  1137.  
  1138.  
  1139. // traiter 1ere ligne d'en tΩte
  1140. void treatfirstline(htsblk* retour,char* rcvd) {
  1141.   char* a=rcvd;
  1142.   // exemple:
  1143.   // HTTP/1.0 200 OK
  1144.   if (*a) {
  1145.     // note: certains serveurs buggΘs renvoient HTTP/1.0\n200 OK ou " HTTP/1.0 200 OK"
  1146.     while ((*a==' ') || (*a==10) || (*a==13) || (*a==9)) a++;      // Θpurer espaces au dΘbut
  1147.     if (strfield(a, "HTTP/")) {
  1148.       // sauter HTTP/1.x
  1149.       while ((*a!=' ') && (*a!='\0') && (*a!=10) && (*a!=13) && (*a!=9)) a++;   
  1150.       if (*a != '\0') {
  1151.         while ((*a==' ') || (*a==10) || (*a==13) || (*a==9)) a++;      // Θpurer espaces
  1152.         if ((*a>='0') && (*a<='9')) {
  1153.           sscanf(a,"%d",&(retour->statuscode));
  1154.           // sauter 200
  1155.           while ((*a!=' ') && (*a!='\0') && (*a!=10) && (*a!=13) && (*a!=9)) a++;   
  1156.           while ((*a==' ') || (*a==10) || (*a==13) || (*a==9)) a++;      // Θpurer espaces
  1157.           if ((strlen(a) > 1) && (strlen(a) < 64) )                // message retour
  1158.             strcpybuff(retour->msg,a);
  1159.           else
  1160.             infostatuscode(retour->msg,retour->statuscode);
  1161.           // type MIME par dΘfaut2
  1162.           strcpybuff(retour->contenttype,HTS_HYPERTEXT_DEFAULT_MIME);
  1163.         } else {  // pas de code!
  1164.           retour->statuscode=-1;
  1165.           strcpybuff(retour->msg,"Unknown response structure");
  1166.         }
  1167.       } else {  // euhh??
  1168.         retour->statuscode=-1;
  1169.         strcpybuff(retour->msg,"Unknown response structure");
  1170.       }
  1171.     } else {
  1172.             if (*a == '<') {
  1173.         /* This is dirty .. */
  1174.         retour->statuscode=200;
  1175.         retour->keep_alive=0;
  1176.         strcpybuff(retour->msg, "Unknown, assuming junky server");
  1177.         strcpybuff(retour->contenttype,HTS_HYPERTEXT_DEFAULT_MIME);
  1178.             } else if (strnotempty(a)) {
  1179.         retour->statuscode=-1;
  1180.         strcpybuff(retour->msg,"Unknown (not HTTP/xx) response structure");
  1181.       } else {
  1182.         /* This is dirty .. */
  1183.         retour->statuscode=200;
  1184.         retour->keep_alive=0;
  1185.         strcpybuff(retour->msg, "Unknown, assuming junky server");
  1186.         strcpybuff(retour->contenttype,HTS_HYPERTEXT_DEFAULT_MIME);
  1187.       }
  1188.     }
  1189.   } else {  // vide!
  1190.     /*
  1191.     retour->statuscode=-1;
  1192.     strcpybuff(retour->msg,"Empty reponse or internal error");
  1193.     */
  1194.     /* This is dirty .. */
  1195.     retour->statuscode=200;
  1196.     strcpybuff(retour->msg, "Unknown, assuming junky server");
  1197.     strcpybuff(retour->contenttype,HTS_HYPERTEXT_DEFAULT_MIME);
  1198.   }
  1199. }
  1200.  
  1201. // traiter ligne par ligne l'en tΩte
  1202. // gestion des cookies
  1203. void treathead(t_cookie* cookie,char* adr,char* fil,htsblk* retour,char* rcvd) {
  1204.   int p;
  1205.   if ((p=strfield(rcvd,"Content-length:"))!=0) {
  1206. #if HDEBUG
  1207.     printf("ok, Content-length: dΘtectΘ\n");
  1208. #endif
  1209.     sscanf(rcvd+p,LLintP,&(retour->totalsize));
  1210.     if (retour->totalsize == 0) {
  1211.       retour->empty = 1;
  1212.     }
  1213.   }
  1214.   else if ((p=strfield(rcvd,"Content-Disposition:"))!=0) {
  1215.     while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1216.     if ((int) strlen(rcvd+p)<250) { // pas trop long?
  1217.       char tmp[256];
  1218.       char *a=NULL,*b=NULL;
  1219.       strcpybuff(tmp,rcvd+p);
  1220.       a=strstr(tmp,"filename=");
  1221.       if (a) {
  1222.         a+=strlen("filename=");
  1223.         while(is_space(*a)) a++;
  1224.         //a=strchr(a,'"');
  1225.         if (a) {
  1226.           char *c=NULL;
  1227.           //a++;      /* jump " */
  1228.           while((c=strchr(a,'/')))    /* skip all / (see RFC2616) */
  1229.             a=c+1;
  1230.           //b=strchr(a+1,'"');
  1231.           b=a+strlen(a)-1;
  1232.           while(is_space(*b)) b--;
  1233.           b++;
  1234.           if (b) {
  1235.             *b='\0';
  1236.             if ((int) strlen(a) < 200) { // pas trop long?
  1237.               strcpybuff(retour->cdispo,a);
  1238.             }
  1239.           }
  1240.         }
  1241.       } 
  1242.     }
  1243.   }
  1244.   else if ((p=strfield(rcvd,"Last-Modified:"))!=0) {
  1245.     while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1246.     if ((int) strlen(rcvd+p)<64) { // pas trop long?
  1247.       //struct tm* tm_time=convert_time_rfc822(rcvd+p);
  1248.       strcpybuff(retour->lastmodified,rcvd+p);
  1249.     }
  1250.   }
  1251.   else if ((p=strfield(rcvd,"Date:"))!=0) {
  1252.     if (strnotempty(retour->lastmodified)==0) {          /* pas encore de last-modified */
  1253.       while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1254.       if ((int) strlen(rcvd+p)<64) { // pas trop long?
  1255.         //struct tm* tm_time=convert_time_rfc822(rcvd+p);
  1256.         strcpybuff(retour->lastmodified,rcvd+p);
  1257.       }
  1258.     }
  1259.   }
  1260.   else if ((p=strfield(rcvd,"Etag:"))!=0) {   /* Etag */
  1261.     if (retour) {
  1262.       while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1263.       if ((int) strlen(rcvd+p)<64)  // pas trop long?
  1264.         strcpybuff(retour->etag,rcvd+p);
  1265.       else    // erreur.. ignorer
  1266.         retour->etag[0]='\0';
  1267.     }
  1268.   }
  1269.   // else if ((p=strfield(rcvd,"Transfer-Encoding: chunked"))!=0) {  // chunk!
  1270.   else if ((p=strfield(rcvd,"Transfer-Encoding:"))!=0) {  // chunk!
  1271.     while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1272.     if (strfield(rcvd+p,"chunked")) {
  1273.       retour->is_chunk=1;     // chunked
  1274.       //retour->http11=2;     // chunked
  1275. #if HDEBUG
  1276.       printf("ok, Transfer-Encoding: dΘtectΘ\n");
  1277. #endif
  1278.     }
  1279.   }
  1280.   else if ((p=strfield(rcvd,"Content-type:"))!=0) {
  1281.     if (retour) {
  1282.       char tempo[1100];
  1283.       // Θviter les text/html; charset=foo
  1284.       {
  1285.         char* a=strchr(rcvd+p,';');
  1286.         if (a) {   // extended information
  1287.           *a='\0';
  1288.           a++;
  1289.               while(is_space(*a)) a++;
  1290.           if (strfield(a, "charset")) {
  1291.             a += 7;
  1292.                 while(is_space(*a)) a++;
  1293.             if (*a == '=') {
  1294.               a++;
  1295.                   while(is_space(*a)) a++;
  1296.               if (*a == '\"') a++;
  1297.                   while(is_space(*a)) a++;
  1298.               if (*a) {
  1299.                 char* chs = a;
  1300.                 while(*a && !is_space(*a) && *a != '\"' && *a != ';') a++;
  1301.                 *a = '\0';
  1302.                 if (*chs) {
  1303.                   if (strlen(chs) < sizeof(retour->charset) - 2) {
  1304.                     strcpybuff(retour->charset, chs);
  1305.                   }
  1306.                 }
  1307.               }
  1308.             }
  1309.           }
  1310.         }
  1311.       }
  1312.       sscanf(rcvd+p,"%s",tempo);
  1313.       if (strlen(tempo) < sizeof(retour->contenttype) - 2)    // pas trop long!!
  1314.         strcpybuff(retour->contenttype,tempo);
  1315.       else
  1316.         strcpybuff(retour->contenttype,"application/octet-stream-unknown");    // erreur
  1317.     }
  1318.   }
  1319.   else if ((p=strfield(rcvd,"Content-Range:"))!=0) {
  1320.     char* a=strstr(rcvd+p,"*/");
  1321.     if (a) {
  1322.       if (sscanf(a+2,LLintP,&retour->crange) != 1) {
  1323.         retour->crange=0;
  1324.       }
  1325.     }
  1326.   }
  1327.   else if ((p=strfield(rcvd,"Connection:"))!=0) {
  1328.         char* a = rcvd + p;
  1329.         while(is_space(*a)) a++;
  1330.         if (*a) {
  1331.             if (strfield(a, "Keep-Alive")) {
  1332.         if (!retour->keep_alive) {
  1333.           retour->keep_alive_max = 10;
  1334.           retour->keep_alive_t = 15;
  1335.         }
  1336.         retour->keep_alive = 1;
  1337.       } else {
  1338.                 retour->keep_alive = 0;
  1339.       }
  1340.         }
  1341.     }
  1342.   else if ((p=strfield(rcvd,"Keep-Alive:"))!=0) {
  1343.         char* a = rcvd + p;
  1344.         while(is_space(*a)) a++;
  1345.         if (*a) {
  1346.       char* p;
  1347.       retour->keep_alive = 1;
  1348.       retour->keep_alive_max = 10;
  1349.       retour->keep_alive_t = 15;
  1350.       if ((p=strstr(a, "timeout="))) {
  1351.         p+=strlen("timeout=");
  1352.         sscanf(p, "%d", &retour->keep_alive_t);
  1353.       }
  1354.       if ((p=strstr(a, "max="))) {
  1355.         p+=strlen("max=");
  1356.         sscanf(p, "%d", &retour->keep_alive_max);
  1357.       }
  1358.       if (retour->keep_alive_max <= 1 || retour->keep_alive_t < 3) {
  1359.         retour->keep_alive = 0;
  1360.       }
  1361.     }
  1362.   }
  1363.   else if ((p=strfield(rcvd,"TE:"))!=0) {
  1364.         char* a = rcvd + p;
  1365.         while(is_space(*a)) a++;
  1366.         if (*a) {
  1367.       if (strfield(a, "trailers")) {
  1368.         retour->keep_alive_trailers=1;
  1369.       }
  1370.     }
  1371.   }
  1372.     else if ((p=strfield(rcvd,"Content-Encoding:"))!=0) {
  1373.         if (retour) {
  1374.             char tempo[1100];
  1375.       char* a = rcvd + p;
  1376.       while(is_space(*a)) a++;
  1377.             {
  1378.                 char* a=strchr(rcvd+p,';');
  1379.                 if (a) *a='\0';
  1380.             }
  1381.             sscanf(a,"%s",tempo);
  1382.       if (strlen(tempo)<64)    // pas trop long!!
  1383.         strcpybuff(retour->contentencoding,tempo);
  1384.       else
  1385.         retour->contentencoding[0]='\0';    // erreur
  1386. #if HTS_USEZLIB
  1387.       /* Check known encodings */
  1388.       if (retour->contentencoding[0]) {
  1389.         if (
  1390.           (strfield2(retour->contentencoding, "gzip"))
  1391.           || (strfield2(retour->contentencoding, "x-gzip"))
  1392.           /*
  1393.           || (strfield2(retour->contentencoding, "compress"))
  1394.           || (strfield2(retour->contentencoding, "x-compress"))
  1395.           */
  1396.           || (strfield2(retour->contentencoding, "deflate"))
  1397.           || (strfield2(retour->contentencoding, "x-deflate"))
  1398.           ) {
  1399.         retour->compressed=1;
  1400.         }
  1401.       }
  1402. #endif
  1403.     }
  1404.   }
  1405.   else if ((p=strfield(rcvd,"Location:"))!=0) {
  1406.     if (retour) {
  1407.       if (retour->location) {
  1408.         while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1409.         if ((int) strlen(rcvd+p)<HTS_URLMAXSIZE)  // pas trop long?
  1410.           strcpybuff(retour->location,rcvd+p);
  1411.         else    // erreur.. ignorer
  1412.           retour->location[0]='\0';
  1413.       }
  1414.     }
  1415.   }
  1416.   else if ( ((p=strfield(rcvd,"Set-Cookie:"))!=0) && (cookie) ) {    // ohh un cookie
  1417.     char* a = rcvd+p;           // pointeur
  1418.     char domain[256];           // domaine cookie (.netscape.com)
  1419.     char path[256];             // chemin (/)
  1420.     char cook_name[256];        // nom cookie (MYCOOK)
  1421.     char cook_value[8192];      // valeur (ID=toto,S=1234)
  1422. #if DEBUG_COOK
  1423.     printf("set-cookie detected\n");
  1424. #endif
  1425.     while(*a) {
  1426.       char *token_st,*token_end;
  1427.       char *value_st,*value_end;
  1428.       char name[256];
  1429.       char value[8192];
  1430.       int next=0;
  1431.       name[0]=value[0]='\0';
  1432.       //
  1433.  
  1434.       // initialiser cookie lu actuellement
  1435.       if (adr)
  1436.         strcpybuff(domain,jump_identification(adr));     // domaine
  1437.       strcpybuff(path,"/");         // chemin (/)
  1438.       strcpybuff(cook_name,"");     // nom cookie (MYCOOK)
  1439.       strcpybuff(cook_value,"");    // valeur (ID=toto,S=1234)
  1440.       // boucler jusqu'au prochain cookie ou la fin
  1441.       do {
  1442.         char* start_loop=a;
  1443.         while(is_space(*a)) a++;    // sauter espaces
  1444.         token_st=a;                 // dΘpart token
  1445.         while((!is_space(*a)) && (*a) && (*a!=';') && (*a!='=')) a++;    // arrΩter si espace, point virgule
  1446.         token_end=a;
  1447.         while(is_space(*a)) a++;    // sauter espaces
  1448.         if (*a=='=') {    // name=value
  1449.           a++;
  1450.           while(is_space(*a)) a++;    // sauter espaces
  1451.           value_st=a;
  1452.           while( (*a!=';') && (*a)) a++;    // prochain ;
  1453.           //while( ((*a!='"') || (*(a-1)=='\\')) && (*a)) a++;    // prochain " (et pas \")
  1454.           value_end=a;
  1455.           //if (*a==';') {  // finit par un ;
  1456.           // vΘrifier dΘbordements
  1457.           if ( (((int) (token_end - token_st))<200) && (((int) (value_end - value_st))<8000)
  1458.             && (((int) (token_end - token_st))>0)   && (((int) (value_end - value_st))>0) ) {
  1459.             name[0]='\0';
  1460.             value[0]='\0';
  1461.             strncatbuff(name,token_st,(int) (token_end - token_st));
  1462.             strncatbuff(value,value_st,(int) (value_end - value_st));
  1463. #if DEBUG_COOK
  1464.             printf("detected cookie-av: name=\"%s\" value=\"%s\"\n",name,value);
  1465. #endif
  1466.             if (strfield2(name,"domain")) {
  1467.               strcpybuff(domain,value);
  1468.             }
  1469.             else if (strfield2(name,"path")) {
  1470.               strcpybuff(path,value);
  1471.             }
  1472.             else if (strfield2(name,"max-age")) {
  1473.               // ignorΘ..
  1474.             }
  1475.             else if (strfield2(name,"expires")) {
  1476.               // ignorΘ..
  1477.             }
  1478.             else if (strfield2(name,"version")) {
  1479.               // ignorΘ..
  1480.             }
  1481.             else if (strfield2(name,"comment")) {
  1482.               // ignorΘ
  1483.             }
  1484.             else if (strfield2(name,"secure")) {    // ne devrait pas arriver ici
  1485.               // ignorΘ
  1486.             }
  1487.             else {
  1488.               if (strnotempty(cook_name)==0) {          // noter premier: nom et valeur cookie
  1489.                 strcpybuff(cook_name,name);
  1490.                 strcpybuff(cook_value,value);
  1491.               } else {                             // prochain cookie
  1492.                 a=start_loop;      // on devra recommencer α cette position
  1493.                 next=1;            // enregistrer
  1494.               }
  1495.             }
  1496.           }
  1497.         }
  1498.         if (!next) {
  1499.           while((*a!=';') && (*a)) a++;    // prochain
  1500.           while(*a==';') a++;             // sauter ;
  1501.         }
  1502.       } while((*a) && (!next));
  1503.       if (strnotempty(cook_name)) {          // cookie?
  1504. #if DEBUG_COOK
  1505.         printf("new cookie: name=\"%s\" value=\"%s\" domain=\"%s\" path=\"%s\"\n",cook_name,cook_value,domain,path);
  1506. #endif
  1507.         cookie_add(cookie,cook_name,cook_value,domain,path);
  1508.       }
  1509.     }
  1510.   }
  1511. }
  1512.  
  1513.  
  1514. // transforme le message statuscode en chaεne
  1515. HTSEXT_API void infostatuscode(char* msg,int statuscode) {
  1516.   switch( statuscode) {    
  1517.     // Erreurs HTTP, selon RFC
  1518.   case 100: strcpybuff( msg,"Continue"); break; 
  1519.   case 101: strcpybuff( msg,"Switching Protocols"); break; 
  1520.   case 200: strcpybuff( msg,"OK"); break; 
  1521.   case 201: strcpybuff( msg,"Created"); break; 
  1522.   case 202: strcpybuff( msg,"Accepted"); break; 
  1523.   case 203: strcpybuff( msg,"Non-Authoritative Information"); break; 
  1524.   case 204: strcpybuff( msg,"No Content"); break; 
  1525.   case 205: strcpybuff( msg,"Reset Content"); break; 
  1526.   case 206: strcpybuff( msg,"Partial Content"); break; 
  1527.   case 300: strcpybuff( msg,"Multiple Choices"); break; 
  1528.   case 301: strcpybuff( msg,"Moved Permanently"); break; 
  1529.   case 302: strcpybuff( msg,"Moved Temporarily"); break; 
  1530.   case 303: strcpybuff( msg,"See Other"); break; 
  1531.   case 304: strcpybuff( msg,"Not Modified"); break; 
  1532.   case 305: strcpybuff( msg,"Use Proxy"); break; 
  1533.   case 306: strcpybuff( msg,"Undefined 306 error"); break; 
  1534.   case 307: strcpybuff( msg,"Temporary Redirect"); break; 
  1535.   case 400: strcpybuff( msg,"Bad Request"); break; 
  1536.   case 401: strcpybuff( msg,"Unauthorized"); break; 
  1537.   case 402: strcpybuff( msg,"Payment Required"); break; 
  1538.   case 403: strcpybuff( msg,"Forbidden"); break; 
  1539.   case 404: strcpybuff( msg,"Not Found"); break; 
  1540.   case 405: strcpybuff( msg,"Method Not Allowed"); break; 
  1541.   case 406: strcpybuff( msg,"Not Acceptable"); break; 
  1542.   case 407: strcpybuff( msg,"Proxy Authentication Required"); break; 
  1543.   case 408: strcpybuff( msg,"Request Time-out"); break; 
  1544.   case 409: strcpybuff( msg,"Conflict"); break; 
  1545.   case 410: strcpybuff( msg,"Gone"); break; 
  1546.   case 411: strcpybuff( msg,"Length Required"); break; 
  1547.   case 412: strcpybuff( msg,"Precondition Failed"); break; 
  1548.   case 413: strcpybuff( msg,"Request Entity Too Large"); break; 
  1549.   case 414: strcpybuff( msg,"Request-URI Too Large"); break; 
  1550.   case 415: strcpybuff( msg,"Unsupported Media Type"); break; 
  1551.   case 416: strcpybuff( msg,"Requested Range Not Satisfiable"); break; 
  1552.   case 417: strcpybuff( msg,"Expectation Failed"); break; 
  1553.   case 500: strcpybuff( msg,"Internal Server Error"); break; 
  1554.   case 501: strcpybuff( msg,"Not Implemented"); break; 
  1555.   case 502: strcpybuff( msg,"Bad Gateway"); break; 
  1556.   case 503: strcpybuff( msg,"Service Unavailable"); break; 
  1557.   case 504: strcpybuff( msg,"Gateway Time-out"); break; 
  1558.   case 505: strcpybuff( msg,"HTTP Version Not Supported"); break; 
  1559.     //
  1560.   default: if (strnotempty(msg)==0) strcpybuff( msg,"Unknown error"); break;
  1561.   }
  1562. }
  1563.  
  1564.  
  1565. // identique au prΘcΘdent, sauf que l'on donne adr+fil et non url complΦte
  1566. htsblk xhttpget(char* adr,char* fil) {
  1567.   T_SOC soc;
  1568.   htsblk retour;
  1569.   
  1570.   memset(&retour, 0, sizeof(htsblk));
  1571.   soc=http_fopen(adr,fil,&retour);
  1572.  
  1573.   if (soc!=INVALID_SOCKET) {
  1574.     http_fread(soc,&retour);
  1575. #if HTS_DEBUG_CLOSESOCK
  1576.     DEBUG_W("xhttpget: deletehttp\n");
  1577. #endif
  1578.     if (retour.soc!=INVALID_SOCKET) deletehttp(&retour);  // fermer
  1579.     retour.soc=INVALID_SOCKET;
  1580.   }
  1581.   return retour;
  1582. }
  1583.  
  1584. // variation sur un thΦme...
  1585. // rΘceptionne uniquement un en-tΩte (HEAD)
  1586. // retourne dans xx.adr l'adresse pointant sur le bloc de mΘmoire de l'en tΩte
  1587. htsblk http_gethead(char* adr,char* fil) {
  1588.   T_SOC soc;
  1589.   htsblk retour;
  1590.  
  1591.   memset(&retour, 0, sizeof(htsblk));
  1592.   soc=http_xfopen(1,0,1,NULL,adr,fil,&retour);  // HEAD, pas de traitement en-tΩte
  1593.  
  1594.   if (soc!=INVALID_SOCKET) {
  1595.     http_fread(soc,&retour);    // rΘception en-tΩte
  1596. #if HTS_DEBUG_CLOSESOCK
  1597.     DEBUG_W("http_gethead: deletehttp\n");
  1598. #endif
  1599.     if (retour.soc!=INVALID_SOCKET) deletehttp(&retour);  // fermer
  1600.     retour.soc=INVALID_SOCKET;
  1601.   }
  1602.   return retour;
  1603. }
  1604. // oui ca ressemble vachement α xhttpget - en Θtant sobre on peut voir LA diffΘrence..
  1605.  
  1606.  
  1607. // lecture sur une socket ouverte, le header a dΘja ΘtΘ envoyΘ dans le cas de GET
  1608. // il ne reste plus qu'α lire les donnΘes
  1609. // (pour HEAD le header est lu ici!)
  1610. void http_fread(T_SOC soc,htsblk* retour) {  
  1611.   //int bufl=TAILLE_BUFFER;    // 8Ko de buffer
  1612.   
  1613.   if (retour) retour->soc=soc;
  1614.   if (soc!=INVALID_SOCKET) {    
  1615.     // fonction de lecture d'une socket (plus propre)
  1616.     while(http_fread1(retour)!=-1);
  1617.     soc=retour->soc;
  1618.     if (retour->adr==NULL) {
  1619.       if (strnotempty(retour->msg)==0)
  1620.         sprintf(retour->msg,"Unable to read");
  1621.       return ;    // erreur
  1622.     } 
  1623.     
  1624. #if HDEBUG
  1625.     printf("Ok, donnΘes reτues\n");
  1626. #endif   
  1627.  
  1628.     return ;
  1629.     
  1630.   } 
  1631.   
  1632.   return ;
  1633. }
  1634.  
  1635. // check if data is available
  1636. int check_readinput(htsblk* r) {
  1637.   if (r->soc != INVALID_SOCKET) {
  1638.     fd_set fds;           // poll structures
  1639.     struct timeval tv;          // structure for select
  1640.     FD_ZERO(&fds);
  1641.     FD_SET(r->soc,&fds);           
  1642.     tv.tv_sec=0;
  1643.     tv.tv_usec=0;
  1644.     select(r->soc + 1,&fds,NULL,NULL,&tv);
  1645.     if (FD_ISSET(r->soc,&fds))
  1646.       return 1;
  1647.     else
  1648.       return 0;
  1649.   } else
  1650.     return 0;
  1651. }
  1652.  
  1653. // check if data is available
  1654. int check_readinput_t(T_SOC soc, int timeout) {
  1655.   if (soc != INVALID_SOCKET) {
  1656.     fd_set fds;           // poll structures
  1657.     struct timeval tv;          // structure for select
  1658.     FD_ZERO(&fds);
  1659.     FD_SET(soc,&fds);           
  1660.     tv.tv_sec=timeout;
  1661.     tv.tv_usec=0;
  1662.     select(soc + 1,&fds,NULL,NULL,&tv);
  1663.     if (FD_ISSET(soc,&fds))
  1664.       return 1;
  1665.     else
  1666.       return 0;
  1667.   } else
  1668.     return 0;
  1669. }
  1670.  
  1671.  
  1672. // lecture d'un bloc sur une socket (ou un fichier!)
  1673. // >=0 : nombre d'octets lus
  1674. // <0 : fin ou erreur
  1675. HTS_INLINE LLint http_fread1(htsblk* r) {
  1676.   //int bufl=TAILLE_BUFFER;  // taille d'un buffer max.
  1677.   return http_xfread1(r,TAILLE_BUFFER);
  1678. }
  1679.  
  1680. // idem, sauf qu'ici on peut choisir la taille max de donnΘes α recevoir
  1681. // SI bufl==0 alors le buffer est censΘ Ωtre de 8kos, et on recoit par bloc de lignes
  1682. // en Θliminant les cr (ex: header), arrΩt si double-lf
  1683. // SI bufl==-1 alors le buffer est censΘ Ωtre de 8kos, et on recoit ligne par ligne
  1684. // en Θliminant les cr (ex: header), arrΩt si double-lf
  1685. // Note: les +1 dans les malloc sont d√s α l'octet nul rajoutΘ en fin de fichier
  1686. LLint http_xfread1(htsblk* r,int bufl) {
  1687.   int nl=-1;
  1688.  
  1689.   if (bufl>0) {
  1690.     if (!r->is_write) {     // stocker en mΘmoire
  1691.       if (r->totalsize>0) {    // totalsize dΘterminΘ ET ALLOUE
  1692.         if (r->adr==NULL) {
  1693.           r->adr=(char*) malloct((INTsys) r->totalsize + 1);
  1694.           r->size=0;
  1695.         }
  1696.         if (r->adr!=NULL) {
  1697.           // lecture
  1698.           nl = hts_read(r,r->adr + ((int) r->size),(int) (r->totalsize-r->size) );     /* NO 32 bit overlow possible here (no 4GB html!) */
  1699.           // nouvelle taille
  1700.           if (nl >= 0) r->size+=nl;
  1701.           
  1702.           if ((nl < 0) || (r->size >= r->totalsize))
  1703.             nl=-1;  // break
  1704.           
  1705.           r->adr[r->size]='\0';    // caractΦre NULL en fin au cas o∙ l'on traite des HTML
  1706.         }
  1707.         
  1708.       } else {                 // inconnu..
  1709.         // rΘserver de la mΘmoire?
  1710.         if (r->adr==NULL) {
  1711. #if HDEBUG
  1712.           printf("..alloc xfread\n");
  1713. #endif
  1714.           r->adr=(char*) malloct(bufl + 1);
  1715.           r->size=0;
  1716.         }
  1717.         else {
  1718. #if HDEBUG
  1719.           printf("..realloc xfread1\n");
  1720. #endif
  1721.           r->adr=(char*) realloct(r->adr,(int)r->size+bufl + 1);
  1722.         }
  1723.         
  1724.         if (r->adr!=NULL) {
  1725.           // lecture
  1726.           nl = hts_read(r,r->adr+(int)r->size,bufl);
  1727.           if (nl>0) {
  1728.             // resize
  1729.             r->adr=(char*) realloct(r->adr,(int)r->size+nl + 1);
  1730.             // nouvelle taille
  1731.             r->size+=nl;
  1732.             // octet nul
  1733.             if (r->adr) r->adr[r->size]='\0';
  1734.  
  1735.           } // sinon on a fini
  1736. #if HDEBUG
  1737.           else if (nl < 0)
  1738.             printf("..end read (%d)\n", nl);
  1739. #endif
  1740.         }
  1741. #if HDEBUG
  1742.         else printf("..-> error\n");
  1743. #endif
  1744.       }
  1745.  
  1746.       // pas de adr=erreur
  1747.       if (r->adr==NULL) nl=-1;
  1748.  
  1749.     } else {    // stocker sur disque
  1750.       char* buff;
  1751.       buff=(char*) malloct(bufl);
  1752.       if (buff!=NULL) {
  1753.         // lecture
  1754.         nl = hts_read(r,buff,bufl);
  1755.         // nouvelle taille
  1756.         if (nl > 0) { 
  1757.           r->size+=nl;
  1758.           if ((INTsys)fwrite(buff,1,nl,r->out)!=nl) {
  1759.             r->statuscode=-1;
  1760.             strcpybuff(r->msg,"Write error on disk");
  1761.             nl=-1;
  1762.           }
  1763.         }
  1764.  
  1765.         if ((nl < 0) || ((r->totalsize>0) && (r->size >= r->totalsize)))
  1766.           nl=-1;  // break
  1767.  
  1768.         // libΘrer bloc tempo
  1769.         freet(buff);
  1770.       } else
  1771.         nl=-1;
  1772.       
  1773.       if ((nl < 0) && (r->out!=NULL)) {
  1774.         fflush(r->out); 
  1775.       }
  1776.         
  1777.         
  1778.     } // stockage disque ou mΘmoire
  1779.  
  1780.   } else if (bufl == -2) {  // force reserve
  1781.     if (r->adr==NULL) {
  1782.       r->adr=(char*) malloct(8192);
  1783.       r->size=0;
  1784.       return 0;
  1785.     }
  1786.     return -1;
  1787.   } else {    // rΘception d'un en-tΩte octet par octet
  1788.     int count=256;
  1789.     int tot_nl=0;
  1790.     int lf_detected=0;
  1791.     int at_begining=1;
  1792.     do {
  1793.       nl=-1;
  1794.       count--;
  1795.       if (r->adr==NULL) {
  1796.         r->adr=(char*) malloct(8192);
  1797.         r->size=0;
  1798.       }
  1799.       if (r->adr!=NULL) {
  1800.         if (r->size < 8190) {
  1801.           // lecture
  1802.           nl = hts_read(r,r->adr+r->size,1);
  1803.           if (nl>0) {
  1804.             // exit if:
  1805.             // lf detected AND already detected before
  1806.             // or
  1807.             // lf detected AND first character read
  1808.             if (*(r->adr+r->size) == 10) {
  1809.               if (lf_detected || (at_begining) || (bufl<0))
  1810.                 count=-1;
  1811.               lf_detected=1;
  1812.             }
  1813.             if (*(r->adr+r->size) != 13) {   // sauter caractΦres 13
  1814.               if (
  1815.                 (*(r->adr+r->size) != 10)
  1816.                 &&
  1817.                 (*(r->adr+r->size) != 13)
  1818.                 ) {
  1819.                 // restart for new line
  1820.                 lf_detected=0;
  1821.               }
  1822.               (r->size)++;
  1823.               at_begining=0;
  1824.             }
  1825.             *(r->adr+r->size)='\0';    // terminer par octet nul
  1826.           }
  1827.         }
  1828.       }
  1829.       if (nl >= 0) {
  1830.         tot_nl+=nl;
  1831.         if (!check_readinput(r))
  1832.           count=-1;
  1833.       }
  1834.     } while((nl >= 0) && (count>0));
  1835.     nl = tot_nl;
  1836.   }
  1837. #if HDEBUG
  1838.   //printf("add to %d / %d\n",r->size,r->totalsize);
  1839. #endif
  1840.   // nl == 0 may mean "no relevant data", for example is using cache or ssl
  1841. #if HTS_USEOPENSSL
  1842.   if (r->ssl)
  1843.     return nl;
  1844.   else
  1845. #endif
  1846.     return ((nl > 0) ? nl : -1);        // ==0 is fatal if direct read
  1847. }
  1848.  
  1849.  
  1850. // teste une adresse, et suit l'Θventuel chemin "moved"
  1851. // retourne 200 ou le code d'erreur (404=NOT FOUND, etc)
  1852. // copie dans loc la vΘritable adresse si celle-ci est diffΘrente
  1853. htsblk http_location(char* adr,char* fil,char* loc) {
  1854.   htsblk retour;
  1855.   int retry=0;
  1856.   int tryagain;
  1857.   // note: "RFC says"
  1858.   // 5 boucles au plus, on en teste au plus 8 ici
  1859.   // sinon abandon..
  1860.   do {
  1861.     tryagain=0;
  1862.     switch ((retour=http_test(adr,fil,loc)).statuscode) {
  1863.     case 200: break;   // ok!
  1864.     case 301: case 302: case 303: case 307: // moved!
  1865.       // recalculer adr et fil!
  1866.       if (ident_url_absolute(loc,adr,fil)!=-1) {
  1867.         tryagain=1;  // retenter
  1868.         retry++;     // ..encore une fois
  1869.       }
  1870.     }
  1871.   } while((tryagain) && (retry<5+3));
  1872.   return retour;
  1873. }
  1874.  
  1875.  
  1876. // teste si une URL (validitΘ, header, taille)
  1877. // retourne 200 ou le code d'erreur (404=NOT FOUND, etc)
  1878. // en cas de moved xx, dans location
  1879. // abandonne dΘsormais au bout de 30 secondes (aurevoir les sites
  1880. // qui nous font poireauter 5 heures..) -> -2=timeout
  1881. htsblk http_test(char* adr,char* fil,char* loc) {
  1882.   T_SOC soc;
  1883.   htsblk retour;
  1884.   //int rcvsize=-1;
  1885.   //char* rcv=NULL;    // adresse de retour
  1886.   //int bufl=TAILLE_BUFFER;    // 8Ko de buffer
  1887.   TStamp tl;
  1888.   int timeout=30;  // timeout pour un check (arbitraire) // **
  1889.  
  1890.   // pour abandonner un site trop lent
  1891.   tl=time_local();
  1892.  
  1893.   loc[0]='\0';
  1894.   memset(&retour, 0, sizeof(htsblk));    // effacer
  1895.   retour.location=loc;    // si non nul, contiendra l'adresse vΘritable en cas de moved xx
  1896.  
  1897.   //soc=http_fopen(adr,fil,&retour,NULL);  // ouvrir, + header
  1898.  
  1899.   // on ouvre en head, et on traite l'en tΩte
  1900.   soc=http_xfopen(1,0,1,NULL,adr,fil,&retour);  // ouvrir HEAD, + envoi header
  1901.   
  1902.   if (soc!=INVALID_SOCKET) {
  1903.     int e=0;
  1904.     // tant qu'on a des donnΘes, et qu'on ne recoit pas deux LF, et que le timeout n'arrie pas
  1905.     do {
  1906.       if (http_xfread1(&retour,0) < 0)
  1907.         e=1;
  1908.       else {
  1909.         if (retour.adr!=NULL) {
  1910.           if ((retour.adr[retour.size-1]!=10) || (retour.adr[retour.size-2]!=10))
  1911.             e=1;
  1912.         }
  1913.       }
  1914.             
  1915.       if (!e) {
  1916.         if ((time_local()-tl)>=timeout) {
  1917.           e=-1;
  1918.         }
  1919.       }
  1920.       
  1921.     } while (!e);
  1922.     
  1923.     if (e==1) {
  1924.       if (adr!=NULL) {
  1925.         int ptr=0;
  1926.         char rcvd[1100];
  1927.  
  1928.         // note: en gros recopie du traitement de back_wait()
  1929.         //
  1930.  
  1931.  
  1932.         // ----------------------------------------
  1933.         // traiter en-tΩte!
  1934.         // status-line α rΘcupΘrer
  1935.         ptr+=binput(retour.adr+ptr,rcvd,1024);
  1936.         if (strnotempty(rcvd)==0)
  1937.           ptr+=binput(retour.adr+ptr,rcvd,1024);    // "certains serveurs buggΘs envoient un \n au dΘbut" (RFC)
  1938.         
  1939.         // traiter status-line
  1940.         treatfirstline(&retour,rcvd);
  1941.         
  1942. #if HDEBUG
  1943.         printf("(Buffer) Status-Code=%d\n",retour.statuscode);
  1944. #endif
  1945.         
  1946.         // en-tΩte
  1947.         
  1948.         // header // ** !attention! HTTP/0.9 non supportΘ
  1949.         do {
  1950.           ptr+=binput(retour.adr+ptr,rcvd,1024);          
  1951. #if HDEBUG
  1952.           printf("(buffer)>%s\n",rcvd);      
  1953. #endif
  1954.           if (strnotempty(rcvd))
  1955.             treathead(NULL,NULL,NULL,&retour,rcvd);  // traiter
  1956.           
  1957.         } while(strnotempty(rcvd));
  1958.         // ----------------------------------------                    
  1959.         
  1960.         // libΘrer mΘmoire
  1961.         if (retour.adr!=NULL) { freet(retour.adr); retour.adr=NULL; }
  1962.       }
  1963.     } else {
  1964.       retour.statuscode=-2;
  1965.       strcpybuff(retour.msg,"Timeout While Testing");
  1966.     }
  1967.     
  1968.     
  1969. #if HTS_DEBUG_CLOSESOCK
  1970.     DEBUG_W("http_test: deletehttp\n");
  1971. #endif
  1972.     deletehttp(&retour);
  1973.     retour.soc=INVALID_SOCKET;
  1974.   }
  1975.   return retour;    
  1976. }
  1977.  
  1978. // CrΘe un lien (http) vers une adresse internet iadr
  1979. // retour: structure (adresse, taille, message si erreur (si !adr))
  1980. // peut ouvrir avec des connect() non bloquants: waitconnect=0/1
  1981. int newhttp(char* _iadr,htsblk* retour,int port,int waitconnect) {  
  1982.   t_fullhostent fullhostent_buffer;    // buffer pour resolver
  1983.   T_SOC soc;                           // descipteur de la socket
  1984.   char* iadr;
  1985.   // unsigned short int port;
  1986.   
  1987.   // si iadr="#" alors c'est une fausse URL, mais un vrai fichier
  1988.   // local.
  1989.   // utile pour les tests!
  1990.   //## if (iadr[0]!=lOCAL_CHAR) {
  1991.   if (strcmp(_iadr,"file://") != 0) {           /* non fichier */
  1992.     SOCaddr server;
  1993.     int server_size=sizeof(server);
  1994.     t_hostent* hp;    
  1995.     // effacer structure
  1996.     memset(&server, 0, sizeof(server));
  1997.  
  1998.     // tester un Θventuel id:pass et virer id:pass@ si dΘtectΘ
  1999.     iadr = jump_identification(_iadr);
  2000.   
  2001. #if HDEBUG
  2002.     printf("gethostbyname\n");
  2003. #endif
  2004.     
  2005.     // tester un Θventuel port
  2006.     if (port==-1) {
  2007.       char *a=jump_toport(iadr);
  2008. #if HTS_USEOPENSSL
  2009.       if (retour->ssl)
  2010.         port=443;
  2011.       else
  2012.         port=80;    // port par dΘfaut
  2013. #else
  2014.       port=80;    // port par dΘfaut
  2015. #endif
  2016.       if (a) {
  2017.         char iadr2[HTS_URLMAXSIZE*2];
  2018.         int i=-1;
  2019.         iadr2[0]='\0';
  2020.         sscanf(a+1,"%d",&i);
  2021.         if (i!=-1) {
  2022.           port=(unsigned short int) i;
  2023.         }
  2024.         
  2025.         // adresse vΘritable (sans :xx)
  2026.         strncatbuff(iadr2,iadr,(int) (a - iadr));
  2027.  
  2028.         // adresse sans le :xx
  2029.         hp = hts_gethostbyname(iadr2, &fullhostent_buffer);
  2030.         
  2031.       } else {
  2032.  
  2033.         // adresse normale (port par dΘfaut par la suite)
  2034.         hp = hts_gethostbyname(iadr, &fullhostent_buffer);
  2035.         
  2036.       }
  2037.       
  2038.     } else    // port dΘfini
  2039.       hp = hts_gethostbyname(iadr, &fullhostent_buffer);
  2040.  
  2041.     
  2042.     // Conversion iadr -> adresse
  2043.     // structure recevant le nom de l'h⌠te, etc
  2044.     //struct     hostent     *hp;
  2045.     if (hp == NULL) {
  2046. #if DEBUG
  2047.       printf("erreur gethostbyname\n");
  2048. #endif
  2049.       if (retour)
  2050.       if (retour->msg)
  2051.         strcpybuff(retour->msg,"Unable to get server's address");
  2052.       return INVALID_SOCKET;
  2053.     }  
  2054.     // copie adresse
  2055.     SOCaddr_copyaddr(server, server_size, hp->h_addr_list[0], hp->h_length);
  2056.     // make a copy for external clients
  2057.     retour->address_size = sizeof(retour->address);
  2058.     SOCaddr_copyaddr(retour->address, retour->address_size, hp->h_addr_list[0], hp->h_length);
  2059.     // memcpy(&SOCaddr_sinaddr(server), hp->h_addr_list[0], hp->h_length);
  2060.      
  2061.     // crΘer ("attachement") une socket (point d'accΦs) internet,en flot
  2062. #if HDEBUG
  2063.     printf("socket\n");
  2064. #endif
  2065. #if HTS_WIDE_DEBUG    
  2066.     DEBUG_W("socket\n");
  2067. #endif
  2068.     soc=socket(SOCaddr_sinfamily(server), SOCK_STREAM, 0);
  2069.     if (retour != NULL) {
  2070.       retour->debugid = HTS_STAT.stat_sockid++;
  2071.     }
  2072. #if HTS_WIDE_DEBUG    
  2073.     DEBUG_W("socket()=%d\n" _ (int) soc);
  2074. #endif
  2075.     if (soc==INVALID_SOCKET) {
  2076.       if (retour)
  2077.       if (retour->msg)
  2078.         strcpybuff(retour->msg,"Unable to create a socket");
  2079.       return INVALID_SOCKET;                        // erreur crΘation socket impossible
  2080.     }
  2081.  
  2082.     // bind this address
  2083.     if (retour != NULL && retour->req.proxy.bindhost[0] != '\0') {
  2084.       t_fullhostent bind_buffer;
  2085.       hp = hts_gethostbyname(retour->req.proxy.bindhost, &bind_buffer);
  2086.       if (hp == NULL ||
  2087.         bind(soc, (struct sockaddr *)hp->h_addr_list[0], hp->h_length) != 0) {
  2088.         if (retour)
  2089.           if (retour->msg)
  2090.             strcpybuff(retour->msg,"Unable to bind the specificied server address");
  2091.           deletesoc(soc);
  2092.           return INVALID_SOCKET;
  2093.       }
  2094.     }
  2095.     
  2096.     // structure: connexion au domaine internet, port 80 (ou autre)
  2097.     SOCaddr_initport(server, port);
  2098. #if HDEBUG
  2099.     printf("==%d\n",soc);
  2100. #endif
  2101.  
  2102.     // connexion non bloquante?
  2103.     if (!waitconnect ) {
  2104.       unsigned long p=1;  // non bloquant
  2105. #if HTS_WIN
  2106.       ioctlsocket(soc,FIONBIO,&p);
  2107. #else
  2108.       ioctl(soc,FIONBIO,&p);
  2109. #endif
  2110.     }
  2111.     
  2112.     // Connexion au serveur lui mΩme
  2113. #if HDEBUG
  2114.     printf("connect\n");
  2115. #endif
  2116.     
  2117. #if HTS_WIDE_DEBUG
  2118.     DEBUG_W("connect\n");
  2119. #endif
  2120. #if HTS_WIN
  2121.     if (connect(soc, (const struct sockaddr FAR *)&server, server_size) != 0) {
  2122. #else
  2123.       if (connect(soc, (struct sockaddr *)&server, server_size) == -1) {
  2124. #endif
  2125.  
  2126.         // bloquant
  2127.         if (waitconnect) {
  2128. #if HDEBUG
  2129.           printf("unable to connect!\n");
  2130. #endif
  2131.           if (retour)
  2132.           if (retour->msg)
  2133.             strcpybuff(retour->msg,"Unable to connect to the server");
  2134.           /* Close the socket and notify the error!!! */
  2135.           deletesoc(soc);
  2136.           return INVALID_SOCKET;
  2137.         }
  2138.       }
  2139. #if HTS_WIDE_DEBUG    
  2140.       DEBUG_W("connect done\n");
  2141. #endif
  2142.       
  2143. #if HDEBUG
  2144.       printf("connexion Θtablie\n");
  2145. #endif
  2146.     
  2147.     // A partir de maintenant, on peut envoyer et recevoir des donnΘes
  2148.     // via le flot identifiΘ par soc (socket): write(soc,adr,taille) et 
  2149.     // read(soc,adr,taille)
  2150.  
  2151.   } else {    // on doit ouvrir un fichier local!
  2152.     // il sera gΘrΘ de la mΩme maniΦre qu'une socket (c'est idem!)
  2153.  
  2154.     soc=LOCAL_SOCKET_ID;    // pseudo-socket locale..
  2155.     // soc sera remplacΘ lors d'un http_fopen() par un handle vΘritable!
  2156.  
  2157.   }   // teste fichier local ou http
  2158.   
  2159.   return soc;
  2160. }
  2161.  
  2162.  
  2163.  
  2164. // couper http://www.truc.fr/pub/index.html -> www.truc.fr /pub/index.html
  2165. // retour=-1 si erreur.
  2166. // si file://... alors adresse=file:// (et coupe le ?query dans ce cas)
  2167. int ident_url_absolute(char* url,char* adr,char* fil) {
  2168.   int pos=0;
  2169.   int scheme=0;
  2170.  
  2171.   // effacer adr et fil
  2172.   adr[0]=fil[0]='\0';
  2173.   
  2174. #if HDEBUG
  2175.   printf("protocol: %s\n",url);
  2176. #endif
  2177.  
  2178.   // Scheme?
  2179.   {
  2180.     char* a=url;
  2181.     while (isalpha((unsigned char)*a))
  2182.       a++;
  2183.     if (*a == ':')
  2184.       scheme=1;
  2185.   }
  2186.  
  2187.   // 1. optional scheme ":"
  2188.   if ((pos=strfield(url,"file:"))) {    // fichier local!! (pour les tests)
  2189.     //!!p+=3;
  2190.     strcpybuff(adr,"file://");
  2191.   } else if ((pos=strfield(url,"http:"))) {    // HTTP
  2192.     //!!p+=3;
  2193.   } else if ((pos=strfield(url,"ftp:"))) {    // FTP
  2194.     strcpybuff(adr,"ftp://");    // FTP!!
  2195.     //!!p+=3;
  2196. #if HTS_USEOPENSSL
  2197.   } else if (SSL_is_available && (pos=strfield(url,"https:"))) {    // HTTPS
  2198.     strcpybuff(adr,"https://");
  2199. #endif
  2200.   } else if (scheme) {
  2201.     return -1;    // erreur non reconnu
  2202.   } else
  2203.     pos=0;
  2204.  
  2205.   // 2. optional "//" authority
  2206.   if (strncmp(url+pos,"//",2)==0)
  2207.     pos+=2;
  2208.  
  2209.   // (url+pos) now points to the path (not net path)
  2210.  
  2211.   //## if (adr[0]!=lOCAL_CHAR) {    // adresse normale http
  2212.   if (!strfield(adr,"file:")) {      // PAS file://
  2213.     char *p,*q;
  2214.     p=url+pos;
  2215.  
  2216.     // p pointe sur le dΘbut de l'adresse, ex: www.truc.fr/sommaire/index.html
  2217.     q=strchr(jump_identification(p),'/');
  2218.     if (q==0) q=strchr(jump_identification(p),'?');     // http://www.foo.com?bar=1
  2219.     if (q==0) q=p+strlen(p);  // pointe sur \0
  2220.     // q pointe sur le chemin, ex: index.html?query=recherche
  2221.     
  2222.     // chemin www... trop long!!
  2223.     if ( ( ((int) (q - p)) )  > HTS_URLMAXSIZE) {
  2224.       //strcpybuff(retour.msg,"Path too long");
  2225.       return -1;    // erreur
  2226.     }
  2227.     
  2228.     // recopier adresse www..
  2229.     strncatbuff(adr,p, ((int) (q - p)) );
  2230.     // *( adr+( ((int) q) - ((int) p) ) )=0;  // faut arrΩter la fumette!
  2231.     // recopier chemin /pub/..
  2232.     if (q[0] != '/')    // page par dΘfaut (/)
  2233.       strcatbuff(fil,"/");
  2234.     strcatbuff(fil,q);
  2235.     // SECURITE:
  2236.     // simplifier url pour les ../
  2237.     fil_simplifie(fil);
  2238.   } else {    // localhost file://
  2239.     char *p;
  2240.     int i;
  2241.     char* a;
  2242.     
  2243.     p=url+pos;
  2244.     if (*p == '/' || *p == '\\') {  /* file:///.. */
  2245.       strcatbuff(fil,p);    // fichier local ; adr="#"
  2246.     } else {
  2247.       if (p[1] != ':') {
  2248.         strcatbuff(fil,"//");   /* file://server/foo */
  2249.         strcatbuff(fil,p);
  2250.       } else {
  2251.         strcatbuff(fil,p);    // file://C:\..
  2252.       }
  2253.     }
  2254.     
  2255.     a=strchr(fil,'?');
  2256.     if (a) 
  2257.       *a='\0';      /* couper query (inutile pour file:// lors de la requΩte) */
  2258.     // filtrer les \\ -> / pour les fichiers DOS
  2259.     for(i=0;i<(int) strlen(fil);i++)
  2260.       if (fil[i]=='\\')
  2261.         fil[i]='/';
  2262.   }
  2263.  
  2264.   // no hostname
  2265.   if (!strnotempty(adr))
  2266.     return -1;    // erreur non reconnu
  2267.  
  2268.   // nommer au besoin.. (non utilisΘ normalement)
  2269.   if (!strnotempty(fil))
  2270.     strcpybuff(fil,"default-index.html");
  2271.  
  2272.   // case insensitive pour adresse
  2273.   {
  2274.     char *a=jump_identification(adr);
  2275.     while(*a) {
  2276.       if ((*a>='A') && (*a<='Z'))
  2277.         *a+='a'-'A';       
  2278.       a++;
  2279.     }
  2280.   }
  2281.   
  2282.   return 0;
  2283. }
  2284.  
  2285. // simplification des ../
  2286. void fil_simplifie(char* f) {
  2287.   int i=0;
  2288.   int last=0;
  2289.   char* a;
  2290.  
  2291.   // Θliminer ../
  2292.   while (f[i]) {
  2293.     if (f[i]=='?')          // query string: that's all, folks!
  2294.       break;
  2295.     if (f[i]=='/') {
  2296.       if (f[i+1]=='.')
  2297.       if (f[i+2]=='.')      // couper dernier rΘpertoire
  2298.       if (f[i+3]=='/')      // Θviter les /tmp/..coolandlamedir/
  2299.       {    // couper dernier rΘpertoire
  2300.         char tempo[HTS_URLMAXSIZE*2];
  2301.         tempo[0]='\0';
  2302.         //
  2303.         if (!last)                /* can't go upper.. */
  2304.           strcpybuff(tempo,"/");
  2305.         else
  2306.           strncpy(tempo,f,last+1);
  2307.         tempo[last+1]='\0';
  2308.         strcatbuff(tempo,f+i+4);
  2309.         strcpybuff(f,tempo);    // remplacer
  2310.         i=-1;             // recommencer
  2311.         last=0;
  2312.       }
  2313.       
  2314.       if (i>=0)
  2315.         last=i;
  2316.       else
  2317.         last=0;
  2318.     }
  2319.     
  2320.     i++;
  2321.   }
  2322.   
  2323.   // Θliminer ./
  2324.   while ( (a=strstr_limit(f,"./","?")) ) {
  2325.     char tempo[HTS_URLMAXSIZE*2];
  2326.     tempo[0]='\0';
  2327.     strcpybuff(tempo,a+2);
  2328.     strcpybuff(a,tempo);
  2329.   }
  2330.   // delete all remaining ../ (potential threat)
  2331.   while ( (a=strstr_limit(f,"../","?")) ) {
  2332.     char tempo[HTS_URLMAXSIZE*2];
  2333.     tempo[0]='\0';
  2334.     strcpybuff(tempo,a+3);
  2335.     strcpybuff(a,tempo);
  2336.   }
  2337.   
  2338. }
  2339.  
  2340. // fermer liaison fichier ou socket
  2341. HTS_INLINE void deletehttp(htsblk* r) {
  2342. #if HTS_DEBUG_CLOSESOCK
  2343.     DEBUG_W("deletehttp: (htsblk*) 0x%p\n" _ (void*) r);
  2344. #endif
  2345. #if HTS_USEOPENSSL
  2346.     /* Free OpenSSL structures */
  2347.     if (SSL_is_available && r->ssl_con) {
  2348.       SSL_shutdown(r->ssl_con);
  2349.       SSL_free(r->ssl_con);
  2350.       r->ssl_con=NULL;
  2351.     }
  2352. #endif  
  2353.   if (r->soc!=INVALID_SOCKET) {
  2354.     if (r->is_file) {
  2355.       if (r->fp)
  2356.         fclose(r->fp);
  2357.       r->fp=NULL;
  2358.     } else {
  2359.       if (r->soc!=LOCAL_SOCKET_ID)
  2360.         deletesoc_r(r);
  2361.     }
  2362.     r->soc=INVALID_SOCKET;
  2363.   }
  2364. }
  2365.  
  2366. // free the addr buffer
  2367. // always returns 1
  2368. HTS_INLINE int deleteaddr(htsblk* r) {
  2369.   if (r->adr != NULL) {
  2370.     freet(r->adr);
  2371.     r->adr = NULL;
  2372.   }
  2373.   if (r->headers != NULL) {
  2374.     freet(r->headers);
  2375.     r->headers = NULL;
  2376.   }
  2377.   return 1;
  2378. }
  2379.  
  2380. // fermer une socket
  2381. HTS_INLINE void deletesoc(T_SOC soc) {
  2382.   if (soc!=INVALID_SOCKET && soc!=LOCAL_SOCKET_ID) {
  2383. #if HTS_WIDE_DEBUG    
  2384.     DEBUG_W("close %d\n" _ (int) soc);
  2385. #endif
  2386. #if HTS_WIN
  2387.     closesocket(soc);
  2388. #else
  2389.     close(soc);
  2390. #endif
  2391. #if HTS_WIDE_DEBUG    
  2392.     DEBUG_W(".. done\n");
  2393. #endif
  2394.   }
  2395. }
  2396.  
  2397. /* Will also clean other things */
  2398. HTS_INLINE void deletesoc_r(htsblk* r) {
  2399. #if HTS_USEOPENSSL
  2400.   if (SSL_is_available && r->ssl_con) {
  2401.     SSL_shutdown(r->ssl_con);
  2402.     // SSL_CTX_set_quiet_shutdown(r->ssl_con->ctx, 1);
  2403.     SSL_free(r->ssl_con);
  2404.     r->ssl_con=NULL;
  2405.   }
  2406. #endif
  2407.   if (r->soc!=INVALID_SOCKET) {
  2408.     deletesoc(r->soc);
  2409.     r->soc=INVALID_SOCKET;
  2410.   }
  2411. }
  2412.  
  2413. // renvoi le nombre de secondes depuis 1970
  2414. HTS_INLINE TStamp time_local(void) {
  2415.   return ((TStamp) time(NULL));
  2416. }
  2417.  
  2418. // number of millisec since 1970
  2419. HTSEXT_API HTS_INLINE TStamp mtime_local(void) {
  2420. #ifndef HTS_DO_NOT_USE_FTIME
  2421.   struct timeb B;
  2422.   ftime( &B );
  2423.   return (TStamp) ( ((TStamp) B.time * (TStamp) 1000)
  2424.         + ((TStamp) B.millitm) );
  2425. #else
  2426.   // not precise..
  2427.   return (TStamp) ( ((TStamp) time_local() * (TStamp) 1000)
  2428.         + ((TStamp) 0) );
  2429. #endif
  2430. }
  2431.  
  2432. // convertit un nombre de secondes en temps (chaine)
  2433. void sec2str(char *st,TStamp t) {
  2434.   int j,h,m,s;
  2435.   
  2436.   j=(int) (t/(3600*24));
  2437.   t-=((TStamp) j)*(3600*24);
  2438.   h=(int) (t/(3600));
  2439.   t-=((TStamp) h)*3600;
  2440.   m=(int) (t/60);
  2441.   t-=((TStamp) m)*60;
  2442.   s=(int) t;
  2443.   
  2444.   if (j>0)
  2445.     sprintf(st,"%d days, %d hours %d minutes %d seconds",j,h,m,s);
  2446.   else if (h>0)
  2447.     sprintf(st,"%d hours %d minutes %d seconds",h,m,s);
  2448.   else if (m>0)
  2449.     sprintf(st,"%d minutes %d seconds",m,s);
  2450.   else
  2451.     sprintf(st,"%d seconds",s);
  2452. }
  2453.  
  2454. // idem, plus court (chaine)
  2455. HTSEXT_API void qsec2str(char *st,TStamp t) {
  2456.   int j,h,m,s;
  2457.   
  2458.   j=(int) (t/(3600*24));
  2459.   t-=((TStamp) j)*(3600*24);
  2460.   h=(int) (t/(3600));
  2461.   t-=((TStamp) h)*3600;
  2462.   m=(int) (t/60);
  2463.   t-=((TStamp) m)*60;
  2464.   s=(int) t;
  2465.   
  2466.   if (j>0)
  2467.     sprintf(st,"%dd,%02dh,%02dmin%02ds",j,h,m,s);
  2468.   else if (h>0)
  2469.     sprintf(st,"%dh,%02dmin%02ds",h,m,s);
  2470.   else if (m>0)
  2471.     sprintf(st,"%dmin%02ds",m,s);
  2472.   else
  2473.     sprintf(st,"%ds",s);
  2474. }
  2475.  
  2476.  
  2477. // heure actuelle, GMT, format rfc (taille buffer 256o)
  2478. void time_gmt_rfc822(char* s) {
  2479.   time_t tt;
  2480.   struct tm* A;
  2481.   tt=time(NULL);
  2482.   A=gmtime(&tt);
  2483.   if (A==NULL)
  2484.     A=localtime(&tt);
  2485.   time_rfc822(s,A);
  2486. }
  2487.  
  2488. // heure actuelle, format rfc (taille buffer 256o)
  2489. void time_local_rfc822(char* s) {
  2490.   time_t tt;
  2491.   struct tm* A;
  2492.   tt=time(NULL);
  2493.   A=localtime(&tt);
  2494.   time_rfc822_local(s,A);
  2495. }
  2496.  
  2497. /* convertir une chaine en temps */
  2498. struct tm* convert_time_rfc822(char* s) {
  2499.   struct tm* result;
  2500.   /* */
  2501.   char months[]="jan feb mar apr may jun jul aug sep oct nov dec";
  2502.   char str[256];
  2503.   char* a;
  2504.   /* */
  2505.   int result_mm=-1;
  2506.   int result_dd=-1;
  2507.   int result_n1=-1;
  2508.   int result_n2=-1;
  2509.   int result_n3=-1;
  2510.   int result_n4=-1;
  2511.   /* */
  2512.   NOSTATIC_RESERVE(result, struct tm, 1);
  2513.  
  2514.   if ((int) strlen(s) > 200)
  2515.     return NULL;
  2516.   strcpybuff(str,s);
  2517.   hts_lowcase(str);
  2518.   /* Θliminer :,- */
  2519.   while( (a=strchr(str,'-')) ) *a=' ';
  2520.   while( (a=strchr(str,':')) ) *a=' ';
  2521.   while( (a=strchr(str,',')) ) *a=' ';
  2522.   /* tokeniser */
  2523.   a=str;
  2524.   while(*a) {
  2525.     char *first,*last;
  2526.     char tok[256];
  2527.     /* dΘcouper mot */
  2528.     while(*a==' ') a++;   /* sauter espaces */
  2529.     first=a;
  2530.     while((*a) && (*a!=' ')) a++;
  2531.     last=a;
  2532.     tok[0]='\0';
  2533.     if (first!=last) {
  2534.       char* pos;
  2535.       strncatbuff(tok,first,(int) (last - first));
  2536.       /* analyser */
  2537.       if ( (pos=strstr(months,tok)) ) {               /* month always in letters */
  2538.         result_mm=((int) (pos - months))/4;
  2539.       } else {
  2540.         int number;
  2541.         if (sscanf(tok,"%d",&number) == 1) {      /* number token */
  2542.           if (result_dd<0)                        /* day always first number */
  2543.             result_dd=number;
  2544.           else if (result_n1<0)
  2545.             result_n1=number;
  2546.           else if (result_n2<0)
  2547.             result_n2=number;
  2548.           else if (result_n3<0)
  2549.             result_n3=number;
  2550.           else if (result_n4<0)
  2551.             result_n4=number;
  2552.         }   /* sinon, bruit de fond(+1GMT for exampel) */
  2553.       }
  2554.     }
  2555.   }
  2556.   if ((result_n1>=0) && (result_mm>=0) && (result_dd>=0) && (result_n2>=0) && (result_n3>=0) && (result_n4>=0)) {
  2557.     if (result_n4>=1000) {               /* Sun Nov  6 08:49:37 1994 */
  2558.       result->tm_year=result_n4-1900;
  2559.       result->tm_hour=result_n1;
  2560.       result->tm_min=result_n2;
  2561.       result->tm_sec=max(result_n3,0);
  2562.     } else {                            /* Sun, 06 Nov 1994 08:49:37 GMT or Sunday, 06-Nov-94 08:49:37 GMT */
  2563.       result->tm_hour=result_n2;
  2564.       result->tm_min=result_n3;
  2565.       result->tm_sec=max(result_n4,0);
  2566.       if (result_n1<=50)                /* 00 means 2000 */
  2567.         result->tm_year=result_n1+100;
  2568.       else if (result_n1<1000)          /* 99 means 1999 */
  2569.         result->tm_year=result_n1;
  2570.       else                              /* 2000 */
  2571.         result->tm_year=result_n1-1900;
  2572.     }
  2573.     result->tm_isdst=0;        /* assume GMT */
  2574.     result->tm_yday=-1;        /* don't know */
  2575.     result->tm_wday=-1;        /* don't know */
  2576.     result->tm_mon=result_mm;
  2577.     result->tm_mday=result_dd;
  2578.     return result;
  2579.   }
  2580.   return NULL;
  2581. }
  2582.  
  2583. /* sets file time. -1 if error */
  2584. int set_filetime(char* file,struct tm* tm_time) {
  2585.   struct utimbuf tim;
  2586. #ifndef HTS_DO_NOT_USE_FTIME
  2587.   struct timeb B;
  2588.   B.timezone=0;
  2589.   ftime( &B );
  2590.   tim.actime=tim.modtime=mktime(tm_time) - B.timezone*60; 
  2591. #else
  2592.   // bogus time (GMT/local)..
  2593.   tim.actime=tim.modtime=mktime(tm_time); 
  2594. #endif
  2595.   return utime(file,&tim);
  2596. }
  2597.  
  2598. /* sets file time from RFC822 date+time, -1 if error*/
  2599. int set_filetime_rfc822(char* file,char* date) {
  2600.   struct tm* tm_s=convert_time_rfc822(date);
  2601.   if (tm_s) {
  2602.     return set_filetime(file,tm_s);
  2603.   } else return -1;
  2604. }
  2605.  
  2606. int get_filetime_rfc822(char* file,char* date) {
  2607.   struct stat buf;
  2608.   date[0] = '\0';
  2609.   if (stat(file, &buf) == 0) {
  2610.     struct tm* A;
  2611.     time_t tt = buf.st_mtime;
  2612.     A=gmtime(&tt);
  2613.     if (A==NULL)
  2614.       A=localtime(&tt);
  2615.     time_rfc822(date, A);
  2616.     return 1;
  2617.   }
  2618.   return 0;
  2619. }
  2620.  
  2621. // heure au format rfc (taille buffer 256o)
  2622. HTS_INLINE void time_rfc822(char* s,struct tm * A) {
  2623.   if (A == NULL) {
  2624.     int localtime_returned_null=0;
  2625.     assert(localtime_returned_null);
  2626.   }
  2627.   strftime(s,256,"%a, %d %b %Y %H:%M:%S GMT",A);
  2628. }
  2629.  
  2630. // heure locale au format rfc (taille buffer 256o)
  2631. HTS_INLINE void time_rfc822_local(char* s,struct tm * A) {
  2632.   if (A == NULL) {
  2633.     int localtime_returned_null=0;
  2634.     assert(localtime_returned_null);
  2635.   }
  2636.   strftime(s,256,"%a, %d %b %Y %H:%M:%S",A);
  2637. }
  2638.  
  2639. // conversion en b,Kb,Mb
  2640. HTSEXT_API char* int2bytes(LLint n) {
  2641.   char** a=int2bytes2(n);
  2642.   char* buff;
  2643.   NOSTATIC_RESERVE(buff, char, 256);
  2644.  
  2645.   strcpybuff(buff,a[0]);
  2646.   strcatbuff(buff,a[1]);
  2647.   return concat(buff,"");
  2648. }
  2649.  
  2650. // conversion en b/s,Kb/s,Mb/s
  2651. HTSEXT_API char* int2bytessec(long int n) {
  2652.   char* buff;
  2653.   char** a=int2bytes2(n);
  2654.   NOSTATIC_RESERVE(buff, char, 256);
  2655.  
  2656.   strcpybuff(buff,a[0]);
  2657.   strcatbuff(buff,a[1]);
  2658.   return concat(buff,"/s");
  2659. }
  2660. HTSEXT_API char* int2char(int n) {
  2661.   char* buffer;
  2662.   NOSTATIC_RESERVE(buffer, char, 32);
  2663.   sprintf(buffer,"%d",n);
  2664.   return concat(buffer,"");
  2665. }
  2666.  
  2667. // conversion en b,Kb,Mb, nombre et type sΘparΘs
  2668. // limite: 2.10^9.10^6B
  2669.  
  2670. /* See http://physics.nist.gov/cuu/Units/binary.html */
  2671. #define ToLLint(a) ((LLint)(a))
  2672. #define ToLLintKiB (ToLLint(1024))
  2673. #define ToLLintMiB (ToLLintKiB*ToLLintKiB)
  2674. #ifdef HTS_LONGLONG
  2675. #define ToLLintGiB (ToLLintKiB*ToLLintKiB*ToLLintKiB)
  2676. #define ToLLintTiB (ToLLintKiB*ToLLintKiB*ToLLintKiB*ToLLintKiB)
  2677. #define ToLLintPiB (ToLLintKiB*ToLLintKiB*ToLLintKiB*ToLLintKiB*ToLLintKiB)
  2678. #endif
  2679. typedef struct {
  2680.   char buff1[256];
  2681.   char buff2[32];
  2682.   char* buffadr[2];
  2683. } strc_int2bytes2;
  2684. HTSEXT_API char** int2bytes2(LLint n) {
  2685.   strc_int2bytes2* strc;
  2686.   NOSTATIC_RESERVE(strc, strc_int2bytes2, 1);
  2687.  
  2688.   if (n < ToLLintKiB) {
  2689.     sprintf(strc->buff1,"%d",(int)(LLint)n);
  2690.     strcpybuff(strc->buff2,"B");
  2691.   } else if (n < ToLLintMiB) {
  2692.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/ToLLintKiB)),(int)((LLint)((n%ToLLintKiB)*100)/ToLLintKiB));
  2693.     strcpybuff(strc->buff2,"KiB");
  2694.   }
  2695. #ifdef HTS_LONGLONG
  2696.   else if (n < ToLLintGiB) {
  2697.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintMiB))),(int)((LLint)(((n%(ToLLintMiB))*100)/(ToLLintMiB))));
  2698.     strcpybuff(strc->buff2,"MiB");
  2699.   } else if (n < ToLLintTiB) {
  2700.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintGiB))),(int)((LLint)(((n%(ToLLintGiB))*100)/(ToLLintGiB))));
  2701.     strcpybuff(strc->buff2,"GiB");
  2702.   } else if (n < ToLLintPiB) {
  2703.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintTiB))),(int)((LLint)(((n%(ToLLintTiB))*100)/(ToLLintTiB))));
  2704.     strcpybuff(strc->buff2,"TiB");
  2705.   } else {
  2706.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintPiB))),(int)((LLint)(((n%(ToLLintPiB))*100)/(ToLLintPiB))));
  2707.     strcpybuff(strc->buff2,"PiB");
  2708.   }
  2709. #else
  2710.   else {
  2711.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintMiB))),(int)((LLint)(((n%(ToLLintMiB))*100)/(ToLLintMiB))));
  2712.     strcpybuff(strc->buff2,"MiB");
  2713.   }
  2714. #endif
  2715.   strc->buffadr[0]=strc->buff1;
  2716.   strc->buffadr[1]=strc->buff2;
  2717.   return strc->buffadr;
  2718. }
  2719.  
  2720. #if HTS_WIN
  2721. #else
  2722. // ignore sigpipe?
  2723. int sig_ignore_flag( int setflag ) {     // flag ignore
  2724.   static int flag=0;   /* YES, this one is true static */
  2725.   if (setflag>=0)
  2726.     flag=setflag;
  2727.   return flag;
  2728. }
  2729. #endif
  2730.  
  2731. // envoi de texte (en tΩtes gΘnΘralement) sur la socket soc
  2732. HTS_INLINE int sendc(htsblk* r, char* s) {
  2733.   int n, ssz = (int)strlen(s);
  2734.  
  2735. #if HTS_WIN
  2736. #else
  2737.   sig_ignore_flag(1);
  2738. #endif
  2739. #if HDEBUG
  2740.   write(0,s,ssz);
  2741. #endif
  2742.  
  2743. #if HTS_USEOPENSSL
  2744.   if (SSL_is_available && r->ssl) {
  2745.     n = SSL_write(r->ssl_con, s, ssz);
  2746.   } else
  2747. #endif
  2748.     n = send(r->soc,s,ssz,0);
  2749.  
  2750. #if HTS_WIN
  2751. #else
  2752.   sig_ignore_flag(0);
  2753. #endif
  2754.  
  2755.   return ( n == ssz ) ? n : -1;
  2756. }
  2757.  
  2758.  
  2759. // Remplace read
  2760. int finput(int fd,char* s,int max) {
  2761.   char c;
  2762.   int j=0;
  2763.   do {
  2764.     //c=fgetc(fp);
  2765.     if (read(fd,&c,1)<=0) {
  2766.       c=0;
  2767.     }
  2768.     if (c!=0) {
  2769.       switch(c) {
  2770.       case 10: c=0; break;
  2771.       case 13: break;  // sauter ces caractΦres
  2772.       default: s[j++]=c; break;
  2773.       }
  2774.     }
  2775.   }  while((c!=0) && (j<max-1));
  2776.   s[j]='\0';
  2777.   return j;
  2778.  
  2779. // Like linput, but in memory (optimized)
  2780. int binput(char* buff, char* s, int max) {
  2781.   int count = 0;
  2782.   int destCount = 0;
  2783.  
  2784.   // Note: \0 will return 1
  2785.   while(count < max && buff != NULL && buff[count] != '\0' && buff[count] != '\n') {
  2786.     if (buff[count] != '\r') {
  2787.       s[destCount++] = buff[count];
  2788.     }
  2789.     count++;
  2790.   }
  2791.   s[destCount] = '\0';
  2792.  
  2793.   // then return the supplemental jump offset
  2794.   return count + 1;
  2795.  
  2796. // Lecture d'une ligne (peut Ωtre unicode α priori)
  2797. int linput(FILE* fp,char* s,int max) {
  2798.   int c;
  2799.   int j=0;
  2800.   do {
  2801.     c=fgetc(fp);
  2802.     if (c!=EOF) {
  2803.       switch(c) {
  2804.         case 13: break;  // sauter CR
  2805.         case 10: c=-1; break;
  2806.         case 9: case 12: break;  // sauter ces caractΦres
  2807.         default: s[j++]=(char) c; break;
  2808.       }
  2809.     }
  2810.   }  while((c!=-1) && (c!=EOF) && (j<(max-1)));
  2811.   s[j]='\0';
  2812.   return j;
  2813. }
  2814. int linputsoc(T_SOC soc, char* s, int max) {
  2815.   int c;
  2816.   int j=0;
  2817.   do {
  2818.     unsigned char ch;
  2819.     if (recv(soc, &ch, 1, 0) == 1) {
  2820.       c = ch;
  2821.     } else {
  2822.       c = EOF;
  2823.     }
  2824.     if (c!=EOF) {
  2825.       switch(c) {
  2826.         case 13: break;  // sauter CR
  2827.         case 10: c=-1; break;
  2828.         case 9: case 12: break;  // sauter ces caractΦres
  2829.         default: s[j++]=(char) c; break;
  2830.       }
  2831.     }
  2832.   }  while((c!=-1) && (c!=EOF) && (j<(max-1)));
  2833.   s[j]='\0';
  2834.   return j;
  2835. }
  2836. int linputsoc_t(T_SOC soc, char* s, int max, int timeout) {
  2837.   if (check_readinput_t(soc, timeout)) {
  2838.     return linputsoc(soc, s, max);
  2839.   }
  2840.   return -1;
  2841. }
  2842. int linput_trim(FILE* fp,char* s,int max) {
  2843.   int rlen=0;
  2844.   char* ls=(char*) malloct(max+2);
  2845.   s[0]='\0';
  2846.   if (ls) {
  2847.     char* a;
  2848.     // lire ligne
  2849.     rlen=linput(fp,ls,max);
  2850.     if (rlen) {
  2851.       // sauter espaces et tabs en fin
  2852.       while( (rlen>0) && ((ls[max(rlen-1,0)]==' ') || (ls[max(rlen-1,0)]=='\t')) )
  2853.         ls[--rlen]='\0';
  2854.       // sauter espaces en dΘbut
  2855.       a=ls;
  2856.       while((rlen>0) && ((*a==' ') || (*a=='\t'))) {
  2857.         a++;
  2858.         rlen--;
  2859.       }
  2860.       if (rlen>0) {
  2861.         memcpy(s,a,rlen);      // can copy \0 chars
  2862.         s[rlen]='\0';
  2863.       }
  2864.     }
  2865.     //
  2866.     freet(ls);
  2867.   }
  2868.   return rlen;
  2869. }
  2870. int linput_cpp(FILE* fp,char* s,int max) {
  2871.   int rlen=0;
  2872.   s[0]='\0';
  2873.   do {
  2874.     int ret;
  2875.     if (rlen>0)
  2876.     if (s[rlen-1]=='\\')
  2877.       s[--rlen]='\0';      // couper \ final
  2878.     // lire ligne
  2879.     ret=linput_trim(fp,s+rlen,max-rlen);
  2880.     if (ret>0)
  2881.       rlen+=ret;
  2882.   } while((s[max(rlen-1,0)]=='\\') && (rlen<max));
  2883.   return rlen;
  2884. }
  2885.  
  2886. // idem avec les car spΘciaux
  2887. void rawlinput(FILE* fp,char* s,int max) {
  2888.   int c;
  2889.   int j=0;
  2890.   do {
  2891.     c=fgetc(fp);
  2892.     if (c!=EOF) {
  2893.       switch(c) {
  2894.         case 13: break;  // sauter CR
  2895.         case 10: c=-1; break;
  2896.         default: s[j++]=(char) c; break;
  2897.       }
  2898.     }
  2899.   }  while((c!=-1) && (c!=EOF) && (j<(max-1)));
  2900.   s[j++]='\0';
  2901. }
  2902.  
  2903. //cherche chaine, case insensitive
  2904. char* strstrcase(char *s,char *o) {
  2905.   while((*s) && (strfield(s,o)==0)) s++;
  2906.   if (*s=='\0') return NULL;
  2907.   return s;  
  2908. }
  2909.  
  2910.  
  2911. // Unicode detector
  2912. // See http://www.unicode.org/unicode/reports/tr28/
  2913. // (sect Table 3.1B. Legal UTF-8 Byte Sequences)
  2914. typedef struct {
  2915.   unsigned int pos;
  2916.   unsigned char data[4];
  2917. } t_auto_seq;
  2918.  
  2919. // char between a and b
  2920. #define CHAR_BETWEEN(c, a, b)       ( (c) >= 0x##a ) && ( (c) <= 0x##b )
  2921. // sequence start
  2922. #define SEQBEG                      ( inseq == 0 )
  2923. // in this block
  2924. #define BLK(n,a, b)                 ( (seq.pos >= n) && ((err = CHAR_BETWEEN(seq.data[n], a, b))) )
  2925. #define ELT(n,a)                    BLK(n,a,a)
  2926. // end
  2927. #define SEQEND                      ((ok = 1))
  2928. // sequence started, character will fail if error
  2929. #define IN_SEQ                      ( (inseq = 1) )
  2930. // decoding error
  2931. #define BAD_SEQ                     ( (ok == 0) && (inseq != 0) && (!err) )
  2932. // no sequence started
  2933. #define NO_SEQ                      ( inseq == 0 )
  2934.  
  2935. // is this block an UTF unicode textfile?
  2936. // 0 : no
  2937. // 1 : yes
  2938. // -1: don't know
  2939. int is_unicode_utf8(unsigned char* buffer, unsigned int size) {
  2940.   t_auto_seq seq;
  2941.   unsigned int i;
  2942.   int is_utf=-1;
  2943.  
  2944.   seq.pos=0;
  2945.   for(i=0 ; i < size ; i++) {
  2946.     unsigned int ok=0;
  2947.     unsigned int inseq=0;
  2948.     unsigned int err=0;
  2949.  
  2950.     seq.data[seq.pos]=buffer[i];
  2951.     /**/ if ( SEQBEG && BLK(0,00,7F) && IN_SEQ && SEQEND                                                 ) { }
  2952.     else if ( SEQBEG && BLK(0,C2,DF) && IN_SEQ && BLK(1,80,BF) && SEQEND                                 ) { }
  2953.     else if ( SEQBEG && ELT(0,E0   ) && IN_SEQ && BLK(1,A0,BF) && BLK(2,80,BF) && SEQEND                 ) { }
  2954.     else if ( SEQBEG && BLK(0,E1,EC) && IN_SEQ && BLK(1,80,BF) && BLK(2,80,BF) && SEQEND                 ) { }
  2955.     else if ( SEQBEG && ELT(0,ED   ) && IN_SEQ && BLK(1,80,9F) && BLK(2,80,BF) && SEQEND                 ) { }
  2956.     else if ( SEQBEG && BLK(0,EE,EF) && IN_SEQ && BLK(1,80,BF) && BLK(2,80,BF) && SEQEND                 ) { }
  2957.     else if ( SEQBEG && ELT(0,F0   ) && IN_SEQ && BLK(1,90,BF) && BLK(2,80,BF) && BLK(3,80,BF) && SEQEND ) { }
  2958.     else if ( SEQBEG && BLK(0,F1,F3) && IN_SEQ && BLK(1,80,BF) && BLK(2,80,BF) && BLK(3,80,BF) && SEQEND ) { }
  2959.     else if ( SEQBEG && ELT(0,F4   ) && IN_SEQ && BLK(1,80,8F) && BLK(2,80,BF) && BLK(3,80,BF) && SEQEND ) { }
  2960.     else if ( NO_SEQ ) {    // bad, unknown
  2961.       return 0;
  2962.     }
  2963.     /* */
  2964.     
  2965.     /* Error */
  2966.     if ( BAD_SEQ ) {
  2967.       return 0;
  2968.     }
  2969.  
  2970.     /* unicode character */
  2971.     if (seq.pos > 0)
  2972.       is_utf=1;
  2973.  
  2974.     /* Next */
  2975.     if (ok)
  2976.       seq.pos=0;
  2977.     else
  2978.       seq.pos++;
  2979.  
  2980.     /* Internal error */
  2981.     if (seq.pos >= 4)
  2982.       return 0;
  2983.  
  2984.   }
  2985.  
  2986.   return is_utf;
  2987. }
  2988.  
  2989. void map_characters(unsigned char* buffer, unsigned int size, unsigned int* map) {
  2990.   unsigned int i;
  2991.   memset(map, 0, sizeof(unsigned int) * 256);
  2992.   for(i = 0 ; i < size ; i++) {
  2993.     map[buffer[i]]++;
  2994.   }
  2995. }
  2996.  
  2997.  
  2998. // le fichier est-il un fichier html?
  2999. //  0 : non
  3000. //  1 : oui
  3001. // -1 : on sait pas
  3002. // -2 : on sait pas, pas d'extension
  3003. int ishtml(const char* fil) {
  3004.   const char *a;
  3005.  
  3006.   // patch pour les truc.html?Choix=toto
  3007.   if ( (a=strchr(fil,'?')) )  // paramΦtres?
  3008.     a--;  // pointer juste avant le ?
  3009.   else
  3010.     a=fil+strlen(fil)-1;  // pointer sur le dernier caractΦre
  3011.  
  3012.   if (*a=='/') return -1;    // rΘpertoire, on sait pas!!
  3013.   //if (*a=='/') return 1;    // ok rΘpertoire, html
  3014.  
  3015.   while ( (*a!='.') && (*a!='/')  && ( a > fil)) a--;
  3016.   if (*a=='.') {  // a une extension
  3017.     char fil_noquery[HTS_URLMAXSIZE*2];
  3018.     char* b;
  3019.     fil_noquery[0]='\0';
  3020.     a++;  // pointer sur extension
  3021.     strncatbuff(fil_noquery,a,HTS_URLMAXSIZE);
  3022.     b=strchr(fil_noquery,'?');
  3023.     if (b)
  3024.       *b='\0';
  3025.     return ishtml_ext(fil_noquery);     // retour
  3026.   } else return -2;   // indΘterminΘ, par exemple /truc
  3027. }
  3028.  
  3029. // idem, mais pour uniquement l'extension
  3030. int ishtml_ext(const char* a) {
  3031.   int html=0;  
  3032.   //
  3033.   if (strfield2(a,"html"))       html = 1;
  3034.   else if (strfield2(a,"htm"))   html = 1;
  3035.   else if (strfield2(a,"shtml")) html = 1;
  3036.   else if (strfield2(a,"phtml")) html = 1;
  3037.   else if (strfield2(a,"htmlx")) html = 1;
  3038.   else if (strfield2(a,"shtm"))  html = 1;
  3039.   else if (strfield2(a,"phtm"))  html = 1;
  3040.   else if (strfield2(a,"htmx"))  html = 1;
  3041.   //
  3042.   // insuccΦs..
  3043.   else {
  3044.     switch(is_knowntype(a)) {
  3045.     case 1:
  3046.       html = 0;     // connu, non html
  3047.       break;
  3048.     case 2:
  3049.       html = 1;     // connu, html
  3050.       break;
  3051.     default:
  3052.       html = -1;    // inconnu..
  3053.       break;
  3054.     }
  3055.   }
  3056.   return html;  
  3057. }
  3058.  
  3059. // error (404,500..)
  3060. HTS_INLINE int ishttperror(int err) {
  3061.   switch (err/100) {
  3062.     case 4: case 5: return 1;
  3063.       break;
  3064.   }
  3065.   return 0;
  3066. }
  3067.  
  3068.  
  3069. // retourne le pointeur ou le pointeur + offset si il existe dans la chaine un @ signifiant 
  3070. // une identification
  3071. HTSEXT_API char* jump_identification(char* source) {
  3072.   char *a,*trytofind;
  3073.   if (strcmp(source, "file://") == 0)
  3074.       return source;
  3075.   // rechercher dernier @ (car parfois email transmise dans adresse!)
  3076.   // mais sauter ftp:// Θventuel
  3077.   a = jump_protocol(source);
  3078.   trytofind = strrchr_limit(a, '@', strchr(a,'/'));
  3079.   return (trytofind != NULL)?trytofind:a;
  3080. }
  3081.  
  3082. HTSEXT_API char* jump_normalized(char* source) {
  3083.   if (strcmp(source, "file://") == 0)
  3084.       return source;
  3085.   source = jump_identification(source); 
  3086.   if (strfield(source, "www") && source[3] != '\0') {
  3087.     if (source[3] == '.') {       // www.foo.com -> foo.com
  3088.       source += 4;  
  3089.     } else {                      // www-4.foo.com -> foo.com
  3090.       char* a = source + 3;
  3091.       while(*a && ( isdigit(*a) || *a == '-') ) a++;
  3092.       if (*a == '.') {
  3093.         source = a + 1;
  3094.       }
  3095.     }
  3096.   }
  3097.   return source;  
  3098. }
  3099.  
  3100. static int sortNormFnc(const void * a_, const void * b_) {
  3101.   char** a = (char**) a_;
  3102.   char** b = (char**) b_;
  3103.   return strcmp(*a+1, *b+1);
  3104. }
  3105.  
  3106.  
  3107. HTSEXT_API char* fil_normalized(char* source, char* dest) {
  3108.   char lastc = 0;
  3109.   int gotquery=0;
  3110.   int ampargs=0;
  3111.   int i,j;
  3112.   char* query=NULL;
  3113.   for(i=j=0 ; source[i] != '\0'; i++) {
  3114.     if (!gotquery && source[i] == '?')
  3115.       gotquery=ampargs=1;
  3116.     if ( 
  3117.       (!gotquery && lastc == '/' && source[i] == '/')  // foo//bar -> foo/bar
  3118.       ) {
  3119.     }
  3120.     else {
  3121.       if (gotquery && source[i] == '&') {
  3122.         ampargs++;
  3123.       }
  3124.       dest[j++] = source[i];
  3125.     }
  3126.     lastc = source[i];
  3127.   }
  3128.   dest[j++] = '\0';
  3129.  
  3130.   /* Sort arguments (&foo=1&bar=2 == &bar=2&foo=1) */
  3131.   if (ampargs > 1) {
  3132.     char** amps = malloct(ampargs * sizeof(char*));
  3133.     char* copyBuff = NULL;
  3134.     int qLen=0;
  3135.     assertf(amps != NULL);
  3136.     gotquery = 0;
  3137.     for(i=j=0 ; dest[i] != '\0'; i++) {
  3138.       if ( (gotquery && dest[i] == '&') || ( !gotquery && dest[i] == '?') ) {
  3139.         if (!gotquery) {
  3140.           gotquery=1;
  3141.           query = &dest[i];
  3142.           qLen = (int)strlen(query);
  3143.         }
  3144.         assertf(j < ampargs);
  3145.         amps[j++] = &dest[i];
  3146.         dest[i] = '\0';
  3147.       }
  3148.     }
  3149.     assertf(j == ampargs);
  3150.  
  3151.     /* Sort 'em all */
  3152.     qsort(amps, ampargs, sizeof(char*), sortNormFnc);
  3153.  
  3154.     /* Replace query by sorted query */
  3155.     copyBuff = malloct(qLen + 1);
  3156.     assertf(copyBuff != NULL);
  3157.     copyBuff[0] = '\0';
  3158.     for(i = 0 ; i < ampargs ; i++) {
  3159.       if (i == 0)
  3160.         strcatbuff(copyBuff, "?");
  3161.       else
  3162.         strcatbuff(copyBuff, "&");
  3163.       strcatbuff(copyBuff, amps[i] + 1);
  3164.     }
  3165.     assert((int)strlen(copyBuff) <= qLen);
  3166.     strcpybuff(query, copyBuff);
  3167.  
  3168.     /* Cleanup */
  3169.     freet(amps);
  3170.     freet(copyBuff);
  3171.   }
  3172.   
  3173.   return dest;
  3174. }
  3175.  
  3176. #define endwith(a) ( (len >= (sizeof(a)-1)) ? ( strncmp(dest, a+len-(sizeof(a)-1), sizeof(a)-1) == 0 ) : 0 );
  3177. HTSEXT_API char* adr_normalized(char* source, char* dest) {
  3178.   /* not yet too aggressive (no com<->net<->org checkings) */
  3179.   strcpybuff(dest, jump_normalized(source));
  3180.   return dest;
  3181. }
  3182. #undef endwith
  3183.  
  3184.  
  3185. // find port (:80) or NULL if not found
  3186. // can handle IPV6 addresses
  3187. HTSEXT_API char* jump_toport(char* source) {
  3188.   char *a,*trytofind;
  3189.   a = jump_identification(source);
  3190.   trytofind = strrchr_limit(a, ']', strchr(source, '/'));    // find last ] (http://[3ffe:b80:1234::1]:80/foo.html)
  3191.   a = strchr( (trytofind)?trytofind:a, ':');
  3192.   return a;
  3193. }
  3194.  
  3195. // strrchr, but not too far
  3196. char* strrchr_limit(char* s, char c, char* limit) {
  3197.   if (limit == NULL) {
  3198.     char* p = strrchr(s, c);
  3199.     return p?(p+1):NULL;
  3200.   } else {
  3201.     char *a=NULL, *p;
  3202.     for(;;) {
  3203.       p=strchr((a)?a:s, c);
  3204.       if ((p >= limit) || (p == NULL))
  3205.         return a;
  3206.       a=p+1;
  3207.     }
  3208.   }
  3209. }
  3210.  
  3211. // strrchr, but not too far
  3212. char* strstr_limit(char* s, char* sub, char* limit) {
  3213.   if (limit == NULL) {
  3214.     return strstr(s, sub);
  3215.   } else {
  3216.     char* pos = strstr(s, sub);
  3217.     if (pos != NULL) {
  3218.       char* farpos = strstr(s, limit);
  3219.       if (farpos == NULL || pos < farpos)
  3220.         return pos;
  3221.     }
  3222.   }
  3223.   return NULL;
  3224. }
  3225.  
  3226. // retourner adr sans ftp://
  3227. HTS_INLINE char* jump_protocol(char* source) {
  3228.   int p;
  3229.   // scheme
  3230.   // "Comparisons of scheme names MUST be case-insensitive" (RFC2616)
  3231.   if ((p=strfield(source,"http:")))
  3232.     source+=p;
  3233.   else if ((p=strfield(source,"ftp:")))
  3234.     source+=p;
  3235.   else if ((p=strfield(source,"https:")))
  3236.     source+=p;
  3237.   else if ((p=strfield(source,"file:")))
  3238.     source+=p;
  3239.   // net_path
  3240.   if (strncmp(source,"//",2)==0)
  3241.     source+=2;
  3242.   return source;
  3243. }
  3244.  
  3245. // codage base 64 a vers b
  3246. void code64(unsigned char* a,int size_a,unsigned char* b,int crlf) {
  3247.   int i1=0,i2=0,i3=0,i4=0;
  3248.   int loop=0;
  3249.   unsigned long int store;
  3250.   int n;
  3251.   const char _hts_base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3252.   while(size_a-- > 0) {  
  3253.     // 24 bits
  3254.     n=1; 
  3255.     store = *a++;
  3256.     if (size_a-- > 0) { n=2; store <<= 8; store |= *a++; }
  3257.     if (size_a-- > 0) { n=3; store <<= 8; store |= *a++; }
  3258.     if (n==3) {
  3259.       i4=store & 63;
  3260.       i3=(store>>6) & 63;
  3261.       i2=(store>>12) & 63;
  3262.       i1=(store>>18) & 63;
  3263.     } else if (n==2) {
  3264.       store<<=2;    
  3265.       i3=store & 63;
  3266.       i2=(store>>6) & 63;
  3267.       i1=(store>>12) & 63;
  3268.     } else {
  3269.       store<<=4;
  3270.       i2=store & 63;
  3271.       i1=(store>>6) & 63;
  3272.     }
  3273.     
  3274.     *b++ = _hts_base64[i1];
  3275.     *b++ = _hts_base64[i2];
  3276.     if (n>=2)
  3277.       *b++ = _hts_base64[i3];
  3278.     else
  3279.       *b++ = '=';
  3280.     if (n>=3)
  3281.       *b++ = _hts_base64[i4];
  3282.     else
  3283.       *b++ = '=';
  3284.  
  3285.     if (crlf && ( ( loop += 3 ) % 60) == 0 ) {
  3286.       *b++ = '\r';
  3287.       *b++ = '\n';
  3288.     }
  3289.   }
  3290.   *b++='\0';
  3291. }
  3292.  
  3293. // remplacer " par " etc..
  3294. // buffer MAX 1Ko
  3295. #define strcmpbeg(a, b) strncmp(a, b, strlen(b))
  3296. HTSEXT_API void unescape_amp(char* s) {
  3297.   while(*s) {
  3298.     if (*s=='&') {
  3299.       char* end=strchr(s,';');
  3300.       if ( end && (((int) (end - s)) <= 8) ) {
  3301.         unsigned char c=0;
  3302.         
  3303.         // http://www.w3.org/TR/xhtml-modularization/dtd_module_defs.html
  3304.         if (strcmpbeg(s, "&#") == 0) {
  3305.           int num=0;
  3306.           if ( (s[2] == 'x') || (s[2] == 'X')) {
  3307.             if (sscanf(s+3, "%x", &num) == 1) {
  3308.               c=(unsigned char)num;
  3309.             }
  3310.           } else {
  3311.             if (sscanf(s+2, "%d", &num) == 1) {
  3312.               c=(unsigned char)num;
  3313.             }
  3314.           }
  3315.         } else if (strcmpbeg(s, " ")==0)
  3316.           c=32; // hack - c=160;
  3317.         else if (strcmpbeg(s, "¡")==0)
  3318.           c=161;
  3319.         else if (strcmpbeg(s, "¢")==0)
  3320.           c=162;
  3321.         else if (strcmpbeg(s, "£")==0)
  3322.           c=163;
  3323.         else if (strcmpbeg(s, "¤")==0)
  3324.           c=164;
  3325.         else if (strcmpbeg(s, "¥")==0)
  3326.           c=165;
  3327.         else if (strcmpbeg(s, "¦")==0)
  3328.           c=166;
  3329.         else if (strcmpbeg(s, "§")==0)
  3330.           c=167;
  3331.         else if (strcmpbeg(s, "¨")==0)
  3332.           c=168;
  3333.         else if (strcmpbeg(s, "©")==0)
  3334.           c=169;
  3335.         else if (strcmpbeg(s, "ª")==0)
  3336.           c=170;
  3337.         //else if (strcmpbeg(s, "«")==0)
  3338.         //  c=171;
  3339.         else if (strcmpbeg(s, "¬")==0)
  3340.           c=172;
  3341.         //else if (strcmpbeg(s, "­")==0)
  3342.         //  c=173;
  3343.         else if (strcmpbeg(s, "®")==0)
  3344.           c=174;
  3345.         else if (strcmpbeg(s, "¯")==0)
  3346.           c=175;
  3347.         else if (strcmpbeg(s, "°")==0)
  3348.           c=176;
  3349.         else if (strcmpbeg(s, "±")==0)
  3350.           c=177;
  3351.         else if (strcmpbeg(s, "²")==0)
  3352.           c=178;
  3353.         else if (strcmpbeg(s, "³")==0)
  3354.           c=179;
  3355.         else if (strcmpbeg(s, "´")==0)
  3356.           c=180;
  3357.         else if (strcmpbeg(s, "µ")==0)
  3358.           c=181;
  3359.         else if (strcmpbeg(s, "¶")==0)
  3360.           c=182;
  3361.         else if (strcmpbeg(s, "·")==0)
  3362.           c=183;
  3363.         else if (strcmpbeg(s, "¸")==0)
  3364.           c=184;
  3365.         else if (strcmpbeg(s, "¹")==0)
  3366.           c=185;
  3367.         else if (strcmpbeg(s, "º")==0)
  3368.           c=186;
  3369.         //else if (strcmpbeg(s, "»")==0)
  3370.         //  c=187;
  3371.         else if (strcmpbeg(s, "¼")==0)
  3372.           c=188;
  3373.         else if (strcmpbeg(s, "½")==0)
  3374.           c=189;
  3375.         else if (strcmpbeg(s, "¾")==0)
  3376.           c=190;
  3377.         else if (strcmpbeg(s, "¿")==0)
  3378.           c=191;
  3379.         else if (strcmpbeg(s, "À")==0)
  3380.           c=192;
  3381.         else if (strcmpbeg(s, "Á")==0)
  3382.           c=193;
  3383.         else if (strcmpbeg(s, "Â")==0)
  3384.           c=194;
  3385.         else if (strcmpbeg(s, "Ã")==0)
  3386.           c=195;
  3387.         else if (strcmpbeg(s, "Ä")==0)
  3388.           c=196;
  3389.         else if (strcmpbeg(s, "Å")==0)
  3390.           c=197;
  3391.         else if (strcmpbeg(s, "Æ")==0)
  3392.           c=198;
  3393.         else if (strcmpbeg(s, "Ç")==0)
  3394.           c=199;
  3395.         else if (strcmpbeg(s, "È")==0)
  3396.           c=200;
  3397.         else if (strcmpbeg(s, "É")==0)
  3398.           c=201;
  3399.         else if (strcmpbeg(s, "Ê")==0)
  3400.           c=202;
  3401.         else if (strcmpbeg(s, "Ë")==0)
  3402.           c=203;
  3403.         else if (strcmpbeg(s, "Ì")==0)
  3404.           c=204;
  3405.         else if (strcmpbeg(s, "Í")==0)
  3406.           c=205;
  3407.         else if (strcmpbeg(s, "Î")==0)
  3408.           c=206;
  3409.         else if (strcmpbeg(s, "Ï")==0)
  3410.           c=207;
  3411.         else if (strcmpbeg(s, "Ð")==0)
  3412.           c=208;
  3413.         else if (strcmpbeg(s, "Ñ")==0)
  3414.           c=209;
  3415.         else if (strcmpbeg(s, "Ò")==0)
  3416.           c=210;
  3417.         else if (strcmpbeg(s, "Ó")==0)
  3418.           c=211;
  3419.         else if (strcmpbeg(s, "Ô")==0)
  3420.           c=212;
  3421.         else if (strcmpbeg(s, "Õ")==0)
  3422.           c=213;
  3423.         else if (strcmpbeg(s, "Ö")==0)
  3424.           c=214;
  3425.         else if (strcmpbeg(s, "×")==0)
  3426.           c=215;
  3427.         else if (strcmpbeg(s, "Ø")==0)
  3428.           c=216;
  3429.         else if (strcmpbeg(s, "Ù")==0)
  3430.           c=217;
  3431.         else if (strcmpbeg(s, "Ú")==0)
  3432.           c=218;
  3433.         else if (strcmpbeg(s, "Û")==0)
  3434.           c=219;
  3435.         else if (strcmpbeg(s, "Ü")==0)
  3436.           c=220;
  3437.         else if (strcmpbeg(s, "Ý")==0)
  3438.           c=221;
  3439.         else if (strcmpbeg(s, "Þ")==0)
  3440.           c=222;
  3441.         else if (strcmpbeg(s, "ß")==0)
  3442.           c=223;
  3443.         else if (strcmpbeg(s, "à")==0)
  3444.           c=224;
  3445.         else if (strcmpbeg(s, "á")==0)
  3446.           c=225;
  3447.         else if (strcmpbeg(s, "â")==0)
  3448.           c=226;
  3449.         else if (strcmpbeg(s, "ã")==0)
  3450.           c=227;
  3451.         else if (strcmpbeg(s, "ä")==0)
  3452.           c=228;
  3453.         else if (strcmpbeg(s, "å")==0)
  3454.           c=229;
  3455.         else if (strcmpbeg(s, "æ")==0)
  3456.           c=230;
  3457.         else if (strcmpbeg(s, "ç")==0)
  3458.           c=231;
  3459.         else if (strcmpbeg(s, "è")==0)
  3460.           c=232;
  3461.         else if (strcmpbeg(s, "é")==0)
  3462.           c=233;
  3463.         else if (strcmpbeg(s, "ê")==0)
  3464.           c=234;
  3465.         else if (strcmpbeg(s, "ë")==0)
  3466.           c=235;
  3467.         else if (strcmpbeg(s, "ì")==0)
  3468.           c=236;
  3469.         else if (strcmpbeg(s, "í")==0)
  3470.           c=237;
  3471.         else if (strcmpbeg(s, "î")==0)
  3472.           c=238;
  3473.         else if (strcmpbeg(s, "ï")==0)
  3474.           c=239;
  3475.         else if (strcmpbeg(s, "ð")==0)
  3476.           c=240;
  3477.         else if (strcmpbeg(s, "ñ")==0)
  3478.           c=241;
  3479.         else if (strcmpbeg(s, "ò")==0)
  3480.           c=242;
  3481.         else if (strcmpbeg(s, "ó")==0)
  3482.           c=243;
  3483.         else if (strcmpbeg(s, "ô")==0)
  3484.           c=244;
  3485.         else if (strcmpbeg(s, "õ")==0)
  3486.           c=245;
  3487.         else if (strcmpbeg(s, "ö")==0)
  3488.           c=246;
  3489.         else if (strcmpbeg(s, "÷")==0)
  3490.           c=247;
  3491.         else if (strcmpbeg(s, "ø")==0)
  3492.           c=248;
  3493.         else if (strcmpbeg(s, "ù")==0)
  3494.           c=249;
  3495.         else if (strcmpbeg(s, "ú")==0)
  3496.           c=250;
  3497.         else if (strcmpbeg(s, "û")==0)
  3498.           c=251;
  3499.         else if (strcmpbeg(s, "ü")==0)
  3500.           c=252;
  3501.         else if (strcmpbeg(s, "ý")==0)
  3502.           c=253;
  3503.         else if (strcmpbeg(s, "þ")==0)
  3504.           c=254;
  3505.         else if (strcmpbeg(s, "ÿ")==0)
  3506.           c=255;
  3507.         //        
  3508.         else if (strcmpbeg(s,"&")==0)
  3509.           c='&';
  3510.         else if (strcmpbeg(s,">")==0)
  3511.           c='>';
  3512.         else if (strcmpbeg(s,"«")==0)
  3513.           c='\"';
  3514.         else if (strcmpbeg(s,"<")==0)
  3515.           c='<';
  3516.         else if (strcmpbeg(s," ")==0)
  3517.           c=' ';
  3518.         else if (strcmpbeg(s,""")==0)
  3519.           c='\"';
  3520.         else if (strcmpbeg(s,"»")==0)
  3521.           c='\"';
  3522.         else if (strcmpbeg(s,"­")==0)
  3523.           c='-';
  3524.         else if (strcmpbeg(s,"˜")==0)
  3525.           c='~';
  3526.         // remplacer?
  3527.         if (c) {
  3528.           char buff[HTS_URLMAXSIZE*2];
  3529.           buff[0]=(char) c;
  3530.           strcpybuff(buff+1,end+1);
  3531.           strcpybuff(s,buff);
  3532.         }
  3533.       }
  3534.     }
  3535.     s++;
  3536.   }
  3537. }
  3538.  
  3539. // remplacer %20 par ' ', | par : etc..
  3540. // buffer MAX 1Ko
  3541. HTSEXT_API char* unescape_http(char* s) {
  3542.   char* tempo;
  3543.   int i,j=0;
  3544.   NOSTATIC_RESERVE(tempo, char, HTS_URLMAXSIZE*2);
  3545.   for (i=0;i<(int) strlen(s);i++) {
  3546.     if (s[i]=='%') {
  3547.       i++;
  3548.       tempo[j++]=(char) ehex(s+i);
  3549.       i++;    // sauter 2 caractΦres finalement
  3550.     }
  3551.     /*
  3552.     NON a cause de trucs comme /home/0,1837,1|7|1173|Content,00.html
  3553.     else if (s[i]=='|') {                     // exemple: file:///C|Program%20Files...
  3554.       tempo[j++]=':';
  3555.     }
  3556.     */
  3557.     else
  3558.       tempo[j++]=s[i];
  3559.   }
  3560.   tempo[j++]='\0';
  3561.   return tempo;
  3562. }
  3563.  
  3564. // unescape in URL/URI ONLY what has to be escaped, to form a standard URL/URI
  3565. HTSEXT_API char* unescape_http_unharm(char* s, int no_high) {
  3566.   char* tempo;
  3567.   int i,j=0;
  3568.   NOSTATIC_RESERVE(tempo, char, HTS_URLMAXSIZE*2);
  3569.   for (i=0;i<(int) strlen(s);i++) {
  3570.     if (s[i]=='%') {
  3571.       int nchar=(char) ehex(s+i+1);
  3572.  
  3573.       int test = (  CHAR_RESERVED(nchar)
  3574.                 || CHAR_DELIM(nchar)
  3575.                 || CHAR_UNWISE(nchar)
  3576.                 || CHAR_LOW(nchar)        /* CHAR_SPECIAL */
  3577.                 || CHAR_XXAVOID(nchar) 
  3578.                 || (
  3579.                   (no_high)
  3580.                   &&
  3581.                   CHAR_HIG(nchar)
  3582.                 )
  3583.                 );
  3584.  
  3585.       if (!test) {
  3586.         tempo[j++]=(char) ehex(s+i+1);
  3587.         i+=2;
  3588.       } else {
  3589.         tempo[j++]='%';
  3590.       }
  3591.     }
  3592.     /*
  3593.     NON a cause de trucs comme /home/0,1837,1|7|1173|Content,00.html
  3594.     else if (s[i]=='|') {                     // exemple: file:///C|Program%20Files...
  3595.       tempo[j++]=':';
  3596.     }
  3597.     */
  3598.     else
  3599.       tempo[j++]=s[i];
  3600.   }
  3601.   tempo[j++]='\0';
  3602.   return tempo;
  3603. }
  3604.  
  3605. // remplacer " par %xx etc..
  3606. // buffer MAX 1Ko
  3607. HTSEXT_API void escape_spc_url(char* s) {
  3608.   x_escape_http(s,2);
  3609. }
  3610. // smith / john -> smith%20%2f%20john
  3611. HTSEXT_API void escape_in_url(char* s) {
  3612.   x_escape_http(s,1);
  3613. }
  3614. // smith / john -> smith%20/%20john
  3615. HTSEXT_API void escape_uri(char* s) {
  3616.   x_escape_http(s,3);
  3617. }
  3618. HTSEXT_API void escape_uri_utf(char* s) {
  3619.   x_escape_http(s,30);
  3620. }
  3621. HTSEXT_API void escape_check_url(char* s) {
  3622.   x_escape_http(s,0);
  3623. }
  3624. // same as escape_check_url, but returns char*
  3625. HTSEXT_API char* escape_check_url_addr(char* s) {
  3626.   char* adr;
  3627.   escape_check_url(adr = concat(s,""));
  3628.   return adr;
  3629. }
  3630.  
  3631. // strip all control characters
  3632. HTSEXT_API void escape_remove_control(char* s) {
  3633.   unsigned char* ss = (unsigned char*) s;
  3634.   while(*ss) {
  3635.     if (*ss < 32) {    /* CONTROL characters go away! */
  3636.       char tmp[HTS_URLMAXSIZE*2];
  3637.       strcpybuff(tmp, ss+1);
  3638.       strcpybuff(ss, tmp);
  3639.     } else {
  3640.       ss++;
  3641.     }
  3642.   }
  3643. }
  3644.  
  3645.  
  3646. HTSEXT_API void x_escape_http(char* s,int mode) {
  3647.   while(*s) {
  3648.     int test=0;
  3649.     if (mode == 0)
  3650.       test=(strchr("\" ",*s)!=0);
  3651.     else if (mode==1) {
  3652.       test = (  CHAR_RESERVED(*s)
  3653.              || CHAR_DELIM(*s)
  3654.              || CHAR_UNWISE(*s)
  3655.              || CHAR_SPECIAL(*s)
  3656.              || CHAR_XXAVOID(*s)
  3657.              || CHAR_MARK(*s));
  3658.     }
  3659.     else if (mode==2)
  3660.       test=(strchr(" ",*s)!=0);           // n'escaper que espace
  3661.     else if (mode==3) {                   // Θchapper que ce qui est nΘcessaire
  3662.       test = (
  3663.                 CHAR_SPECIAL(*s)
  3664.              || CHAR_XXAVOID(*s) );
  3665.     }
  3666.     else if (mode==30) {                   // Θchapper que ce qui est nΘcessaire
  3667.       test = (
  3668.                 CHAR_LOW(*s)
  3669.              || CHAR_XXAVOID(*s) );
  3670.     }
  3671.  
  3672.     if (test) {
  3673.       char buffer[HTS_URLMAXSIZE*3];
  3674.       int n;
  3675.       n=(int)(unsigned char) *s;
  3676.       strcpybuff(buffer,s+1);
  3677.       sprintf(s,"%%%02x",n);
  3678.       strcatbuff(s,buffer);
  3679.     }
  3680.     s++;
  3681.   }
  3682. }
  3683.  
  3684.  
  3685. HTS_INLINE int ehexh(char c) {
  3686.   if ((c>='0') && (c<='9')) return c-'0';
  3687.   if ((c>='a') && (c<='f')) c-=('a'-'A');
  3688.   if ((c>='A') && (c<='F')) return (c-'A'+10);
  3689.   return 0;
  3690. }
  3691.  
  3692. HTS_INLINE int ehex(char* s) {
  3693.   return 16*ehexh(*s)+ehexh(*(s+1));
  3694.  
  3695. }
  3696.  
  3697. // concat, concatΦne deux chaines et renvoi le rΘsultat
  3698. // permet d'allΘger grandement le code
  3699. // il faut savoir qu'on ne peut mettre plus de 16 concat() dans une expression
  3700. typedef struct {
  3701.   char buff[16][HTS_URLMAXSIZE*2*2];
  3702.   int rol;
  3703. } concat_strc;
  3704. char* concat(const char* a,const char* b) {
  3705.   concat_strc* strc;
  3706.   NOSTATIC_RESERVE(strc, concat_strc, 1);
  3707.   strc->rol=((strc->rol+1)%16);    // roving pointer
  3708.   strcpybuff(strc->buff[strc->rol],a);
  3709.   if (b) strcatbuff(strc->buff[strc->rol],b);
  3710.   return strc->buff[strc->rol];
  3711. }
  3712. // conversion fichier / -> antislash
  3713. #if HTS_DOSNAME
  3714. char* __fconv(char* a) {
  3715.   int i;
  3716.   for(i=0;i<(int) strlen(a);i++)
  3717.     if (a[i]=='/')  // convertir
  3718.       a[i]='\\';
  3719.   return a;
  3720. }
  3721. char* fconcat(char* a,char* b) {
  3722.   return __fconv(concat(a,b));
  3723. }
  3724. char* fconv(char* a) {
  3725.   return __fconv(concat(a,""));
  3726. }
  3727. #endif
  3728.  
  3729. /* / et \\ en / */
  3730. char* __fslash(char* a) {
  3731.   int i;
  3732.   for(i=0;i<(int) strlen(a);i++)
  3733.     if (a[i]=='\\')  // convertir
  3734.       a[i]='/';
  3735.   return a;
  3736. }
  3737. char* fslash(char* a) {
  3738.   return __fslash(concat(a,""));
  3739. }
  3740.  
  3741. // conversion minuscules, avec buffer
  3742. char* convtolower(char* a) {
  3743.   concat_strc* strc;
  3744.   NOSTATIC_RESERVE(strc, concat_strc, 1);
  3745.   strc->rol=((strc->rol+1)%16);    // roving pointer
  3746.   strcpybuff(strc->buff[strc->rol],a);
  3747.   hts_lowcase(strc->buff[strc->rol]);  // lower case
  3748.   return strc->buff[strc->rol];
  3749. }
  3750.  
  3751. // conversion en minuscules
  3752. void hts_lowcase(char* s) {
  3753.   int i;
  3754.   for(i=0;i<(int) strlen(s);i++)
  3755.     if ((s[i]>='A') && (s[i]<='Z'))
  3756.       s[i]+=('a'-'A');
  3757. }
  3758.  
  3759. // remplacer un caractΦre d'une chaεne dans une autre
  3760. HTS_INLINE void hts_replace(char *s,char from,char to) { 
  3761.   char* a;
  3762.   while ((a=strchr(s,from))!=NULL) {
  3763.     *a=to;
  3764.   }
  3765. }
  3766.  
  3767.  
  3768. // caractΦre espace, guillemets, CR, LF etc..
  3769. /* SECTION OPTIMISEE:
  3770.   #define  is_space(c) (strchr(" \"\x0d\x0a\x09'",c)!=NULL)
  3771.   #define  is_realspace(c) (strchr(" \x0d\x0a\x09\x0c",c)!=NULL)
  3772. */
  3773. /*
  3774. HTS_INLINE int is_space(char c) {
  3775.   if (c==' ')  return 1;  // spc
  3776.   if (c=='"')  return 1;  // quote
  3777.   if (c==10)   return 1;  // lf
  3778.   if (c==13)   return 1;  // cr
  3779.   if (c=='\'') return 1;  // quote
  3780.   //if (c=='`')  return 1;  // backquote      << non
  3781.   if (c==9)    return 1;  // tab
  3782.   return 0;
  3783. }
  3784. */
  3785.  
  3786. // caractΦre espace, CR, LF, TAB
  3787. /*
  3788. HTS_INLINE int is_realspace(char c) {
  3789.   if (c==' ')  return 1;  // spc
  3790.   if (c==10)   return 1;  // lf
  3791.   if (c==13)   return 1;  // cr
  3792.   if (c==9)    return 1;  // tab
  3793.   return 0;
  3794. }
  3795. */
  3796.  
  3797.  
  3798.  
  3799.  
  3800.  
  3801. // deviner type d'un fichier local..
  3802. // ex: fil="toto.gif" -> s="image/gif"
  3803. void guess_httptype(char *s,const char *fil) {
  3804.   get_httptype(s,fil,1);
  3805. }
  3806. // idem
  3807. // flag: 1 si toujours renvoyer un type
  3808. void get_httptype(char *s,const char *fil,int flag) {
  3809.   if (ishtml(fil)==1)
  3810.     strcpybuff(s,"text/html");
  3811.   else {
  3812.     const char *a=fil+strlen(fil)-1;    
  3813.     while ( (*a!='.') && (*a!='/')  && (a>fil)) a--;
  3814.     if (*a=='.' && strlen(a) < 32) {
  3815.       int ok=0;
  3816.       int j=0;
  3817.       a++;
  3818.       while( (!ok) && (strnotempty(hts_mime[j][1])) ) {
  3819.         if (strfield2(hts_mime[j][1],a)) {
  3820.           if (hts_mime[j][0][0]!='*') {    // Une correspondance existe
  3821.             strcpybuff(s,hts_mime[j][0]);
  3822.             ok=1;
  3823.           }
  3824.         }
  3825.         j++;
  3826.       }
  3827.       
  3828.       if (!ok) if (flag) sprintf(s,"application/%s",a);
  3829.     } else {
  3830.       if (flag) strcpybuff(s,"application/octet-stream");
  3831.     }
  3832.   }
  3833. }
  3834.  
  3835. // get type of fil (php)
  3836. // s: buffer (text/html) or NULL
  3837. // return: 1 if known by user
  3838. int get_userhttptype(int setdefs,char *s,const char *ext) {
  3839.   char** buffer=NULL;
  3840.   NOSTATIC_RESERVE(buffer, char*, 1);
  3841.   if (setdefs) {
  3842.     *buffer=s;
  3843.     return 1;
  3844.   } else {
  3845.     if (s)
  3846.       s[0]='\0';
  3847.     if (!ext)
  3848.       return 0;
  3849.     if (*buffer) {
  3850.       char search[1024];
  3851.       char* detect;
  3852.       sprintf(search,"\n%s=",ext);    // php=text/html
  3853.       detect=strstr(*buffer,search);
  3854.       if (!detect) {
  3855.         sprintf(search,"\n%s\n",ext); // php\ncgi=text/html
  3856.         detect=strstr(*buffer,search);
  3857.       }
  3858.       if (detect) {
  3859.         detect=strchr(detect,'=');
  3860.         if (detect) {
  3861.           detect++;
  3862.           if (s) {
  3863.             char* a;
  3864.             a=strchr(detect,'\n');
  3865.             if (a) {
  3866.               strncatbuff(s,detect,(int) (a - detect));
  3867.             }
  3868.           }
  3869.           return 1;
  3870.         }
  3871.       }
  3872.     }
  3873.   }
  3874.   return 0;
  3875. }
  3876. // renvoyer extesion d'un type mime..
  3877. // ex: "image/gif" -> gif
  3878. void give_mimext(char *s,char *st) {   
  3879.   int ok=0;
  3880.   int j=0;
  3881.   s[0]='\0';
  3882.   while( (!ok) && (strnotempty(hts_mime[j][1])) ) {
  3883.     if (strfield2(hts_mime[j][0],st)) {
  3884.       if (hts_mime[j][1][0]!='*') {    // Une correspondance existe
  3885.         strcpybuff(s,hts_mime[j][1]);
  3886.         ok=1;
  3887.       }
  3888.     }
  3889.     j++;
  3890.   }
  3891.   // wrap "x" mimetypes, such as:
  3892.   // application/x-mp3
  3893.   // or
  3894.   // application/mp3
  3895.   if (!ok) {
  3896.     int p;
  3897.     char* a=NULL;
  3898.     if ((p=strfield(st,"application/x-")))
  3899.       a=st+p;
  3900.     else if ((p=strfield(st,"application/")))
  3901.       a=st+p;
  3902.     if (a) {
  3903.       if ((int)strlen(a) >= 1) {
  3904.         if ((int)strlen(a) <= 4) {
  3905.           strcpybuff(s,a);
  3906.           ok=1;
  3907.         }
  3908.       }
  3909.     }
  3910.   }
  3911. }
  3912. // extension connue?..
  3913. //  0 : non
  3914. //  1 : oui
  3915. //  2 : html
  3916. int is_knowntype(const char *fil) {
  3917.   int j=0;
  3918.   if (!fil)
  3919.     return 0;
  3920.   while(strnotempty(hts_mime[j][1])) {
  3921.     if (strfield2(hts_mime[j][1],fil)) {
  3922.       if (strfield2(hts_mime[j][0],"text/html"))
  3923.         return 2;
  3924.       else
  3925.         return 1;
  3926.     }
  3927.     j++;
  3928.   }
  3929.  
  3930.   // Known by user?
  3931.   return (is_userknowntype(fil));
  3932. }
  3933. // extension : html,gif..
  3934. char* get_ext(const char *fil) {
  3935.   char* fil_noquery;
  3936.   const char *a=fil+strlen(fil)-1;    
  3937.   NOSTATIC_RESERVE(fil_noquery, char, HTS_URLMAXSIZE*2);
  3938.  
  3939.   while ( (*a!='.') && (*a!='/')  && (a>fil)) a--;
  3940.   if (*a=='.') {
  3941.     char* b;
  3942.     fil_noquery[0]='\0';
  3943.     a++;  // pointer sur extension
  3944.     strncatbuff(fil_noquery,a,HTS_URLMAXSIZE);
  3945.     b=strchr(fil_noquery,'?');
  3946.     if (b)
  3947.       *b='\0';
  3948.     return concat(fil_noquery,"");
  3949.   }
  3950.   else
  3951.     return "";
  3952. }
  3953. // known type?..
  3954. //  0 : no
  3955. //  1 : yes
  3956. //  2 : html
  3957. // setdefs : set mime buffer:
  3958. //   file=(char*) "asp=text/html\nphp=text/html\n"
  3959. int is_userknowntype(const char *fil) {
  3960.   char mime[1024];
  3961.   if (!fil)
  3962.     return 0;
  3963.   if (!strnotempty(fil))
  3964.     return 0;
  3965.   mime[0]='\0';
  3966.   get_userhttptype(0,mime,fil);
  3967.   if (!strnotempty(mime))
  3968.     return 0;
  3969.   else if (strfield2(mime,"text/html"))
  3970.     return 2;
  3971.   else
  3972.     return 1;
  3973. }
  3974.  
  3975. // page dynamique?
  3976. // is_dyntype(get_ext("foo.asp"))
  3977. int is_dyntype(const char *fil) {
  3978.   int j=0;
  3979.   if (!fil)
  3980.     return 0;
  3981.   if (!strnotempty(fil))
  3982.     return 0;
  3983.   while(strnotempty(hts_ext_dynamic[j])) {
  3984.     if (strfield2(hts_ext_dynamic[j],fil)) {
  3985.       return 1;
  3986.     }
  3987.     j++;
  3988.   }
  3989.   return 0;
  3990. }
  3991.  
  3992. // types critiques qui ne doivent pas Ωtre changΘs car renvoyΘs par des serveurs qui ne
  3993. // connaissent pas le type
  3994. int may_unknown(const char* st) {
  3995.   int j=0;
  3996.   // types mΘdia
  3997.   if (may_be_hypertext_mime(st, "")) {
  3998.     return 1;
  3999.   }
  4000.   while(strnotempty(hts_mime_keep[j])) {
  4001.     if (strfield2(hts_mime_keep[j],st)) {      // trouvΘ
  4002.       return 1;
  4003.     }
  4004.     j++;
  4005.   }    
  4006.   return 0;
  4007. }
  4008.  
  4009.  
  4010. // -- Utils fichiers
  4011.  
  4012. // pretty print for i/o
  4013. void fprintfio(FILE* fp,char* buff,char* prefix) {
  4014.   char nl=1;
  4015.   while(*buff) {
  4016.     switch(*buff) {
  4017.     case 13: break;
  4018.     case 10:
  4019.       fprintf(fp,"\r\n");
  4020.       nl=1;
  4021.     break;
  4022.     default:
  4023.       if (nl)
  4024.         fprintf(fp,prefix);
  4025.       nl=0;
  4026.       fputc(*buff,fp);
  4027.     }
  4028.     buff++;
  4029.   }
  4030. }
  4031.  
  4032. /* Le fichier existe-t-il? (ou est-il accessible?) */
  4033. int fexist(char* s) {
  4034.   struct stat st;
  4035.   memset(&st, 0, sizeof(st));
  4036.   if (stat(s, &st) == 0) {
  4037.     if (S_ISREG(st.st_mode)) {
  4038.       return 1;
  4039.     }
  4040.   }
  4041.   return 0;
  4042.  
  4043. /* Taille d'un fichier, -1 si n'existe pas */
  4044. /* fp->_cnt ne fonctionne pas sur toute les plate-formes :-(( */
  4045. /* Note: NOT YET READY FOR 64-bit */
  4046. INTsys fsize(char* s) {
  4047.   FILE* fp;
  4048.   if (strnotempty(s)==0)     // nom vide: erreur
  4049.     return -1;
  4050.   fp=fopen(fconv(s),"rb");
  4051.   if (fp!=NULL) {
  4052.     INTsys i;
  4053.     fseek(fp,0,SEEK_END);
  4054. #ifdef HTS_FSEEKO
  4055.     i=ftello(fp);
  4056. #else
  4057.     i=ftell(fp);
  4058. #endif
  4059.     fclose(fp);
  4060.     return i;
  4061.   } else return -1;
  4062. }
  4063.  
  4064. INTsys fpsize(FILE* fp) {
  4065.   INTsys oldpos,size;
  4066.   if (!fp)
  4067.     return -1;
  4068. #ifdef HTS_FSEEKO
  4069.   oldpos=ftello(fp);
  4070. #else
  4071.   oldpos=ftell(fp);
  4072. #endif
  4073.   fseek(fp,0,SEEK_END);
  4074. #ifdef HTS_FSEEKO
  4075.   size=ftello(fp);
  4076.   fseeko(fp,oldpos,SEEK_SET);
  4077. #else
  4078.   size=ftell(fp);
  4079.   fseek(fp,oldpos,SEEK_SET);
  4080. #endif
  4081.   return size;
  4082. }
  4083.  
  4084. /* root dir, with ending / */
  4085. typedef struct {
  4086.   char path[1024+4];
  4087.   int init;
  4088. } hts_rootdir_strc;
  4089. HTSEXT_API char* hts_rootdir(char* file) {
  4090.   static hts_rootdir_strc strc = {"", 0};
  4091.   //NOSTATIC_RESERVE(strc, hts_rootdir_strc, 1);
  4092.   if (file) {
  4093.     if (!strc.init) {
  4094.       strc.path[0]='\0';
  4095.       strc.init=1;
  4096.       if (strnotempty(file)) {
  4097.         char* a;
  4098.         strcpybuff(strc.path,file);
  4099.         while((a=strrchr(strc.path,'\\'))) *a='/';
  4100.         if ((a=strrchr(strc.path,'/'))) {
  4101.           *(a+1)='\0';
  4102.         } else
  4103.           strc.path[0]='\0';
  4104.       }
  4105.       if (!strnotempty(strc.path)) {
  4106.         if( getcwd( strc.path, 1024 ) == NULL )
  4107.             strc.path[0]='\0';
  4108.         else
  4109.           strcatbuff(strc.path,"/");
  4110.       }
  4111.     }
  4112.     return NULL;
  4113.   } else if (strc.init)
  4114.     return strc.path;
  4115.   else
  4116.     return "";
  4117. }
  4118.  
  4119.  
  4120.  
  4121. HTSEXT_API hts_stat_struct HTS_STAT;
  4122. //
  4123. // return  number of downloadable bytes, depending on rate limiter
  4124. // see engine_stats() routine, too
  4125. // this routine works quite well for big files and regular ones, but apparently the rate limiter has
  4126. // some problems with very small files (rate too high)
  4127. LLint check_downloadable_bytes(int rate) {
  4128.   if (rate>0) {
  4129.     TStamp time_now;
  4130.     TStamp elapsed_useconds;
  4131.     LLint bytes_transfered_during_period;
  4132.     LLint left;
  4133.  
  4134.     // get the older timer
  4135.     int id_timer = (HTS_STAT.istat_idlasttimer + 1) % 2;
  4136.  
  4137.     time_now=mtime_local();
  4138.     elapsed_useconds = time_now - HTS_STAT.istat_timestart[id_timer];
  4139.     // NO totally stupid - elapsed_useconds+=1000;      // for the next second, too
  4140.     bytes_transfered_during_period = (HTS_STAT.HTS_TOTAL_RECV-HTS_STAT.istat_bytes[id_timer]);
  4141.     
  4142.     left = ((rate * elapsed_useconds)/1000) - bytes_transfered_during_period;
  4143.     if (left <= 0)
  4144.       left = 0;
  4145.     
  4146.     return left;
  4147.   } else
  4148.     return TAILLE_BUFFER;
  4149. }
  4150.  
  4151. //
  4152. // 0 : OK
  4153. // 1 : slow down
  4154. #if 0
  4155. int HTS_TOTAL_RECV_CHECK(int var) {
  4156.   if (HTS_STAT.HTS_TOTAL_RECV_STATE)
  4157.     return 1;
  4158.     /*
  4159.     {
  4160.     if (HTS_STAT.HTS_TOTAL_RECV_STATE==3) { 
  4161.       var = min(var,32); 
  4162.       Sleep(250); 
  4163.     } else if (HTS_STAT.HTS_TOTAL_RECV_STATE==2) { 
  4164.       var = min(var,256); 
  4165.       Sleep(100); 
  4166.     } else { 
  4167.       var/=2; 
  4168.       if (var<=0) var=1; 
  4169.       Sleep(50); 
  4170.     } 
  4171.   }
  4172.     */
  4173.   return 0;
  4174. }
  4175. #endif
  4176.  
  4177. // Lecture dans buff de size octets au maximum en utilisant la socket r (structure htsblk)
  4178. // >0 : data received
  4179. // == 0 : not yet data
  4180. // <0 : no more data or error
  4181. HTS_INLINE int hts_read(htsblk* r,char* buff,int size) {
  4182.   int retour;
  4183.   //  return read(soc,buff,size);
  4184.   if (r->is_file) {
  4185. #if HTS_WIDE_DEBUG    
  4186.     DEBUG_W("read(%p, %d, %d)\n" _ (void*) buff _ (int) size _ (int) r->fp);
  4187. #endif
  4188.     if (r->fp)
  4189.       retour=(int)fread(buff,1,size,r->fp);
  4190.     else
  4191.       retour=-1;
  4192.   } else {
  4193. #if HTS_WIDE_DEBUG    
  4194.     DEBUG_W("recv(%d, %p, %d)\n" _ (int) r->soc _ (void*) buff _ (int) size);
  4195.     if (r->soc==INVALID_SOCKET)
  4196.       printf("!!WIDE_DEBUG ERROR, soc==INVALID hts_read\n");
  4197. #endif
  4198.     //HTS_TOTAL_RECV_CHECK(size);         // Diminuer au besoin si trop de donnΘes reτues
  4199. #if HTS_USEOPENSSL
  4200.     if (SSL_is_available && r->ssl) {
  4201.       retour = SSL_read(r->ssl_con, buff, size);
  4202.       if (retour <= 0) {
  4203.         int err_code = SSL_get_error(r->ssl_con, retour);
  4204.         if (
  4205.           (err_code == SSL_ERROR_WANT_READ)
  4206.           ||
  4207.           (err_code == SSL_ERROR_WANT_WRITE)
  4208.           ) 
  4209.         {
  4210.           retour = 0;             /* no data yet (ssl cache) */
  4211.         } else {
  4212.           retour = -1;            /* eof or error */
  4213.         }
  4214.       }
  4215.     } else {
  4216. #endif
  4217.     retour=recv(r->soc,buff,size,0);
  4218.   }
  4219.   if (retour > 0)    // compter flux entrant
  4220.     HTS_STAT.HTS_TOTAL_RECV+=retour;
  4221. #if HTS_USEOPENSSL
  4222.   }
  4223. #endif
  4224. #if HTS_WIDE_DEBUG    
  4225.   DEBUG_W("recv/read done (%d bytes)\n" _ (int) retour);
  4226. #endif
  4227.   return retour;
  4228. }
  4229.  
  4230.  
  4231. // -- Gestion cache DNS --
  4232. // 'RX98
  4233. #if HTS_DNSCACHE
  4234.  
  4235. // 'capsule' contenant uniquement le cache
  4236. t_dnscache* _hts_cache(void) {
  4237.   t_dnscache* cache;
  4238.   NOSTATIC_RESERVE(cache, t_dnscache, 1);
  4239.   return cache;
  4240. }
  4241. // free the cache
  4242. static void hts_cache_free_(t_dnscache* cache) {
  4243.   if (cache != NULL) {
  4244.     if (cache->n != NULL) {
  4245.       hts_cache_free_(cache->n);
  4246.     }
  4247.     freet(cache);
  4248.   }
  4249. }
  4250. void hts_cache_free(t_dnscache* cache) {
  4251.   if (cache != NULL) {
  4252.     hts_cache_free_(cache->n);
  4253.     cache->n = NULL;
  4254.   }
  4255. }
  4256.  
  4257. // lock le cache dns pour tout opΘration d'ajout
  4258. // plus prudent quand plusieurs threads peuvent Θcrire dedans..
  4259. // -1: status? 0: libΘrer 1:locker
  4260.  
  4261. /* 
  4262.   Simple lock function for cache
  4263.  
  4264.   Return value: always 0
  4265.   Parameter:
  4266.   1 wait for lock (mutex) available and lock it
  4267.   0 unlock the mutex
  4268.   [-1 check if locked (always return 0 with mutex)]
  4269.   -999 initialize
  4270. */
  4271. #if USE_BEGINTHREAD
  4272. int _hts_lockdns(int i) {
  4273.   static PTHREAD_LOCK_TYPE hMutex; 
  4274.   return htsSetLock(&hMutex,i);
  4275. }
  4276. #else
  4277. int _hts_lockdns(int i) {
  4278.   int l=0;
  4279.   if (i>=0)
  4280.     l=i;
  4281.   return l;
  4282. }
  4283. #endif
  4284.  
  4285. // routine pour le cache - retour optionnel α donner α chaque fois
  4286. // NULL: nom non encore testΘ dans le cache
  4287. // si h_length==0 alors le nom n'existe pas dans le dns
  4288. t_hostent* _hts_ghbn(t_dnscache* cache,char* iadr,t_hostent* retour) {
  4289.   // attendre que le cache dns soit prΩt
  4290.   while(_hts_lockdns(-1));  // attendre libΘration
  4291.   _hts_lockdns(1);          // locker
  4292.  
  4293.   while(1) {
  4294.     if (strcmp(cache->iadr,iadr)==0) {  // ok trouvΘ
  4295.       if (cache->host_length>0) {  // entrΘe valide
  4296.         if (retour->h_addr_list[0])
  4297.           memcpy(retour->h_addr_list[0], cache->host_addr, cache->host_length);
  4298.         retour->h_length=cache->host_length;
  4299.       } else if (cache->host_length==0) {  // en cours
  4300.         _hts_lockdns(0);          // dΘlocker
  4301.         return NULL;
  4302.       } else {                    // erreur dans le dns, dΘja vΘrifiΘ
  4303.         if (retour->h_addr_list[0])
  4304.           retour->h_addr_list[0][0]='\0';
  4305.         retour->h_length=0;  // erreur, n'existe pas
  4306.       }
  4307.       _hts_lockdns(0);          // dΘlocker
  4308.       return retour;
  4309.     } else {    // on a pas encore trouvΘ
  4310.       if (cache->n!=NULL) { // chercher encore
  4311.         cache=cache->n;   // suivant!
  4312.       } else {
  4313.         _hts_lockdns(0);          // dΘlocker
  4314.         return NULL;    // non prΘsent        
  4315.       }
  4316.     }    
  4317.   }
  4318. }
  4319.  
  4320. // tester si iadr a dΘja ΘtΘ testΘ (ou en cours de test)
  4321. // 0 non encore
  4322. // 1 ok
  4323. // 2 non prΘsent
  4324. int hts_dnstest(char* _iadr) {
  4325.   char* iadr;
  4326.   t_dnscache* cache=_hts_cache();  // adresse du cache 
  4327.   NOSTATIC_RESERVE(iadr, char, HTS_URLMAXSIZE*2);
  4328.  
  4329.   // sauter user:pass@ Θventuel
  4330.   strcpybuff(iadr,jump_identification(_iadr));
  4331.   // couper Θventuel :
  4332.   {
  4333.     char *a;
  4334.     if ( (a=jump_toport(iadr)) )
  4335.       *a='\0';
  4336.   }
  4337.  
  4338. #if HTS_WIN
  4339.   if (inet_addr(iadr)!=INADDR_NONE)  // numΘrique
  4340. #else
  4341.   if (inet_addr(iadr)!=(in_addr_t) -1 )  // numΘrique
  4342. #endif
  4343.     return 1;
  4344.  
  4345.   while(_hts_lockdns(-1));  // attendre libΘration
  4346.   _hts_lockdns(1);          // locker
  4347.   while(1) {
  4348.     if (strcmp(cache->iadr,iadr)==0) {  // ok trouvΘ
  4349.       _hts_lockdns(0);          // dΘlocker
  4350.       return 1;    // prΘsent!
  4351.     } else {    // on a pas encore trouvΘ
  4352.       if (cache->n!=NULL) { // chercher encore
  4353.         cache=cache->n;   // suivant!
  4354.       } else {
  4355.         _hts_lockdns(0);          // dΘlocker
  4356.         return 2;    // non prΘsent        
  4357.       }
  4358.     }    
  4359.   }
  4360. }
  4361.  
  4362.  
  4363. HTSEXT_API t_hostent* vxgethostbyname(char* hostname, void* v_buffer) {
  4364.   t_fullhostent* buffer = (t_fullhostent*) v_buffer;
  4365.   /* Clear */
  4366.   fullhostent_init(buffer);
  4367.  
  4368.   /* Protection */
  4369.   if (!strnotempty(hostname)) {
  4370.     return NULL;
  4371.   }
  4372.  
  4373.   /* 
  4374.     Strip [] if any : [3ffe:b80:1234:1::1] 
  4375.     The resolver doesn't seem to handle IP6 addresses in brackets
  4376.   */
  4377.   if ((hostname[0] == '[') && (hostname[strlen(hostname)-1] == ']')) {
  4378.     char tempo[HTS_URLMAXSIZE*2];
  4379.     tempo[0]='\0';
  4380.     strncatbuff(tempo, hostname+1, strlen(hostname)-2);
  4381.     strcpybuff(hostname, tempo);
  4382.   }
  4383.  
  4384.   {
  4385. #if HTS_INET6==0
  4386.   /*
  4387.   ipV4 resolver
  4388.     */
  4389.     t_hostent* hp=gethostbyname(hostname);
  4390.     if (hp!=NULL) {
  4391.       if ( (hp->h_length) && ( ((unsigned int) hp->h_length) <= buffer->addr_maxlen) ) {
  4392.         memcpy(buffer->hp.h_addr_list[0], hp->h_addr_list[0], hp->h_length);
  4393.         buffer->hp.h_length = hp->h_length;
  4394.         return &(buffer->hp);
  4395.       }
  4396.     }
  4397. #else
  4398.     /*
  4399.     ipV6 resolver
  4400.     */
  4401.     /*
  4402.     int error_num=0;
  4403.     t_hostent* hp=getipnodebyname(hostname, AF_INET6, AI_DEFAULT, &error_num);
  4404.     oops, deprecated :(
  4405.     */
  4406.     struct addrinfo* res = NULL;
  4407.     struct addrinfo hints;
  4408.     memset(&hints, 0, sizeof(hints));
  4409.     if (IPV6_resolver == 1)        // V4 only (for bogus V6 entries)
  4410.       hints.ai_family = PF_INET;
  4411.     else if (IPV6_resolver == 2)   // V6 only (for testing V6 only)
  4412.       hints.ai_family = PF_INET6;
  4413.     else                           // V4 + V6
  4414.       hints.ai_family = PF_UNSPEC;
  4415.     hints.ai_socktype = SOCK_STREAM;
  4416.     hints.ai_protocol = IPPROTO_TCP;
  4417.     if (getaddrinfo(hostname, NULL, &hints, &res) == 0) {
  4418.       if (res) {
  4419.         if ( (res->ai_addr) && (res->ai_addrlen) && (res->ai_addrlen <= buffer->addr_maxlen) ) {
  4420.           memcpy(buffer->hp.h_addr_list[0], res->ai_addr, res->ai_addrlen);
  4421.           buffer->hp.h_length = res->ai_addrlen;
  4422.           freeaddrinfo(res);
  4423.           return &(buffer->hp);
  4424.         }
  4425.       }
  4426.     }
  4427.     if (res) {
  4428.       freeaddrinfo(res);
  4429.     }
  4430.     
  4431. #endif
  4432.   }
  4433.   return NULL;
  4434. }
  4435.  
  4436. // cache dns interne α HTS // ** FREE A FAIRE sur la chaine
  4437. t_hostent* hts_gethostbyname(char* _iadr, void* v_buffer) {
  4438.   char iadr[HTS_URLMAXSIZE*2];
  4439.   t_fullhostent* buffer = (t_fullhostent*) v_buffer;
  4440.   t_dnscache* cache=_hts_cache();  // adresse du cache
  4441.   t_hostent* hp;
  4442.  
  4443.   /* Clear */
  4444.   fullhostent_init(buffer);
  4445.  
  4446.   strcpybuff(iadr,jump_identification(_iadr));
  4447.   // couper Θventuel :
  4448.   {
  4449.     char *a;
  4450.     if ( (a=jump_toport(iadr)) )
  4451.       *a='\0';
  4452.   }
  4453.  
  4454.   // effacer structure de retour, crΘer nouvelle
  4455.   /*
  4456.   memset(&host, 0, sizeof(t_hostent));  
  4457.   host.h_addr_list=he;
  4458.   he[0]=NULL;
  4459.   he[1]=NULL;  
  4460.   host.h_length=0;  
  4461.   */
  4462.   cache->iadr[0]='*';
  4463.   cache->iadr[1]='\0';
  4464.   
  4465.   /* get IP from the dns cache */
  4466.   hp = _hts_ghbn(cache, iadr, &buffer->hp);
  4467.   if (hp) {
  4468.     if (hp->h_length>0)
  4469.       return hp;
  4470.     else
  4471.       return NULL;    // entrΘe erronΘe (erreur DNS) dans le DNS
  4472.   } else {  // non prΘsent dans le cache dns, tester
  4473.     t_dnscache* c=cache;
  4474.     while(c->n) c=c->n;    // calculer queue
  4475.     
  4476. #if HTS_WIDE_DEBUG    
  4477.     DEBUG_W("gethostbyname\n");
  4478. #endif      
  4479. #if HDEBUG
  4480.     printf("gethostbyname (not in cache)\n");
  4481. #endif
  4482.     {
  4483.       unsigned long inetaddr;
  4484. #if HTS_WIN
  4485.       if ((inetaddr=inet_addr(iadr))==INADDR_NONE) {
  4486. #else
  4487.       if ((inetaddr=inet_addr(iadr))==(in_addr_t) -1 ) {
  4488. #endif        
  4489. #if DEBUGDNS 
  4490.         printf("resolving (not cached) %s\n",iadr);
  4491. #endif
  4492.         hp=vxgethostbyname(iadr, buffer);  // calculer IP host
  4493.       } else {     // numΘrique, convertir sans passer par le dns
  4494.         buffer->hp.h_addr_list[0]=(char*) &inetaddr;
  4495.         buffer->hp.h_length=4;
  4496.         hp=&buffer->hp;
  4497.       }
  4498.     }
  4499. #if HTS_WIDE_DEBUG    
  4500.     DEBUG_W("gethostbyname done\n");
  4501. #endif
  4502.     cache->n=(t_dnscache*) calloct(1,sizeof(t_dnscache));
  4503.     if (cache->n!=NULL) {
  4504.       strcpybuff(cache->n->iadr,iadr);
  4505.       if (hp!=NULL) {
  4506.         memcpy(cache->n->host_addr, hp->h_addr_list[0], hp->h_length);
  4507.         cache->n->host_length=hp->h_length;
  4508.       } else {
  4509.         cache->n->host_addr[0]='\0';
  4510.         cache->n->host_length=0;  // non existant dans le dns
  4511.       }
  4512.       cache->n->n=NULL;
  4513.       return hp;
  4514.     } else {  // on peut pas noter, mais on peut renvoyer le rΘsultat
  4515.       return hp;
  4516.     }        
  4517.   }  // retour hp du cache
  4518. }
  4519.  
  4520. #else
  4521. HTS_INLINE t_hostent* hts_gethostbyname(char* iadr, t_fullhostent* buffer) {
  4522.   t_hostent* retour;
  4523. #if HTS_WIDE_DEBUG    
  4524.   DEBUG_W("gethostbyname (2)\n");
  4525. #endif
  4526. #if DEBUGDNS 
  4527.     printf("blocking method gethostbyname() in progress for %s\n",iadr);
  4528. #endif
  4529.   retour=vxgethostbyname(jump_identification(iadr), );
  4530. #if HTS_WIDE_DEBUG    
  4531.   DEBUG_W("gethostbyname (2) done\n");
  4532. #endif
  4533.   return retour;
  4534. }
  4535. #endif
  4536.  
  4537.  
  4538. // --- Tracage des mallocs() ---
  4539. #ifdef HTS_TRACE_MALLOC
  4540. //#define htsLocker(A, N) htsLocker(A, N)
  4541. #define htsLocker(A, N) do {} while(0)
  4542. static mlink trmalloc = {NULL,0,0,NULL};
  4543. static int trmalloc_id=0;
  4544. static PTHREAD_LOCK_TYPE* mallocMutex = NULL;
  4545. static void hts_meminit(void) {
  4546.   //if (mallocMutex == NULL) {
  4547.   //  mallocMutex = calloc(sizeof(*mallocMutex), 1);
  4548.   //  htsLocker(mallocMutex, -999);
  4549.   //}
  4550. }
  4551. void* hts_malloc(size_t len) {
  4552.   void* adr;
  4553.   hts_meminit();
  4554.   htsLocker(mallocMutex, 1);
  4555.   fassert(len > 0);
  4556.   adr = hts_xmalloc(len, 0);
  4557.   htsLocker(mallocMutex, 0);
  4558.   return adr;
  4559. }
  4560. void* hts_calloc(size_t len,size_t len2) {
  4561.   void* adr;
  4562.   hts_meminit();
  4563.   fassert(len > 0);
  4564.   fassert(len2 > 0);
  4565.   htsLocker(mallocMutex, 1);
  4566.   adr = hts_xmalloc(len, len2);
  4567.   htsLocker(mallocMutex, 0);
  4568.   memset(adr, 0, len * len2);
  4569.   return adr;
  4570. }
  4571. void* hts_strdup(char* str) {
  4572.   size_t size = str ? strlen(str) : 0;
  4573.   char* adr = (char*) hts_malloc(size + 1);
  4574.   fassert(adr != NULL);
  4575.   strcpy(adr, str ? str : "");
  4576.   return adr;
  4577. }
  4578. void* hts_xmalloc(size_t len,size_t len2) {
  4579.   mlink* lnk = (mlink*) calloc(1,sizeof(mlink));
  4580.   fassert(lnk != NULL);
  4581.   fassert(len > 0);
  4582.   fassert(len2 >= 0);
  4583.   if (lnk) {
  4584.     void*  r   = NULL;
  4585.     int size, bsize = sizeof(t_htsboundary);
  4586.     if (len2)
  4587.       size = len * len2;
  4588.     else
  4589.       size = len;
  4590.     size += ((bsize - (size % bsize)) % bsize);  /* check alignement */
  4591.     r = malloc(size + bsize*2);
  4592.     fassert(r != NULL);
  4593.     if (r) {
  4594.       * ( (t_htsboundary*) ((char*) r ) ) 
  4595.         = * ( (t_htsboundary*) ( (char*) r + size + bsize ) )
  4596.         = htsboundary;
  4597.       ((char*) r) += bsize;    /* boundary */
  4598.       lnk->adr = r;
  4599.       lnk->len = size;
  4600.       lnk->id = trmalloc_id++;
  4601.       lnk->next = trmalloc.next;
  4602.       trmalloc.next = lnk;
  4603.       return r;
  4604.     } else {
  4605.       free(lnk);
  4606.     }
  4607.   }
  4608.   return NULL;
  4609. }
  4610. void hts_free(void* adr) {
  4611.   mlink* lnk = &trmalloc;
  4612.   int bsize = sizeof(t_htsboundary);
  4613.   fassert(adr != NULL);
  4614.   if (!adr) {
  4615.     return;
  4616.   }
  4617.   htsLocker(mallocMutex, 1);
  4618.   while(lnk->next != NULL) {
  4619.     if (lnk->next->adr == adr) {
  4620.       mlink* blk_free=lnk->next;
  4621.       fassert(blk_free->id != -1);
  4622.       fassert( * ( (t_htsboundary*) ( (char*) adr - bsize ) ) == htsboundary );
  4623.       fassert( * ( (t_htsboundary*) ( (char*) adr + blk_free->len ) ) == htsboundary );
  4624.       lnk->next=lnk->next->next;
  4625.       free((void*) blk_free);
  4626.       //blk_free->id=-1;
  4627.       free((char*) adr - bsize);
  4628.       htsLocker(mallocMutex, 0);
  4629.       return;
  4630.     }
  4631.     lnk = lnk->next;
  4632.     fassert(lnk->next != NULL);
  4633.   }
  4634.   free(adr);
  4635.   htsLocker(mallocMutex, 0);
  4636. }
  4637. void* hts_realloc(void* adr,size_t len) {
  4638.   int bsize = sizeof(t_htsboundary);
  4639.   len += ((bsize - (len % bsize)) % bsize);  /* check alignement */
  4640.   if (adr != NULL) {
  4641.     mlink* lnk = &trmalloc;
  4642.     htsLocker(mallocMutex, 1);
  4643.     while(lnk->next != NULL)  {
  4644.       if (lnk->next->adr==adr) {
  4645.         {
  4646.           mlink* blk_free=lnk->next;
  4647.           fassert(blk_free->id != -1);
  4648.           fassert( * ( (t_htsboundary*) ( (char*) adr - bsize ) ) == htsboundary );
  4649.           fassert( * ( (t_htsboundary*) ( (char*) adr + blk_free->len ) ) == htsboundary );
  4650.         }
  4651.         adr = realloc((char*) adr - bsize, len + bsize * 2);
  4652.         fassert(adr != NULL);
  4653.         lnk->next->adr = (char*) adr + bsize;
  4654.         lnk->next->len = len;
  4655.         * ( (t_htsboundary*) ( (char*) adr ) ) 
  4656.           = * ( (t_htsboundary*) ( (char*) adr + len + bsize) ) 
  4657.           = htsboundary;
  4658.         htsLocker(mallocMutex, 0);
  4659.         return (char*) adr + bsize;
  4660.       }
  4661.       lnk = lnk->next;
  4662.       fassert(lnk->next != NULL);
  4663.     }
  4664.     htsLocker(mallocMutex, 0);
  4665.   }
  4666.   return hts_malloc(len);
  4667. }
  4668. mlink* hts_find(char* adr) {
  4669.   char* stkframe = (char*) &stkframe;
  4670.   mlink* lnk = &trmalloc;
  4671.   int bsize = sizeof(t_htsboundary);
  4672.   fassert(adr != NULL);
  4673.   if (!adr) {
  4674.     return NULL;
  4675.   }
  4676.   htsLocker(mallocMutex, 1);
  4677.   while(lnk->next != NULL) {
  4678.     if (adr >= lnk->next->adr && adr <= lnk->next->adr + lnk->next->len) {   /* found */
  4679.       htsLocker(mallocMutex, 0);
  4680.       return lnk->next;
  4681.     }
  4682.     lnk = lnk->next;
  4683.   }
  4684.   htsLocker(mallocMutex, 0);
  4685.   {
  4686.     int depl = (int) (adr - stkframe);
  4687.     if (depl < 0) depl = -depl;
  4688.     //fassert(depl < 512000);   /* near the stack frame.. doesn't look like malloc but stack variable */
  4689.     return NULL;
  4690.   }
  4691. }
  4692. // check the malloct() and calloct() trace stack
  4693. void  hts_freeall(void) {
  4694.   int bsize = sizeof(t_htsboundary);
  4695.   while(trmalloc.next) {
  4696. #if MEMDEBUG
  4697.     printf("* block %d\t not released: at %d\t (%d\t bytes)\n",trmalloc.next->id,trmalloc.next->adr,trmalloc.next->len);
  4698. #endif
  4699.     if (trmalloc.next->id != -1) {
  4700.       free((char*) trmalloc.next->adr - bsize);
  4701.     }
  4702.   }
  4703. }
  4704. #endif
  4705.  
  4706.  
  4707. // -- divers //
  4708.  
  4709. // cut path and project name
  4710. // patch also initial path
  4711. void cut_path(char* fullpath,char* path,char* pname) {
  4712.   path[0]=pname[0]='\0';
  4713.   if (strnotempty(fullpath)) {
  4714.     if ((fullpath[strlen(fullpath)-1]=='/') || (fullpath[strlen(fullpath)-1]=='\\'))
  4715.       fullpath[strlen(fullpath)-1]='\0';
  4716.     if (strlen(fullpath)>1) {
  4717.       char* a;
  4718.       while( (a=strchr(fullpath,'\\')) ) *a='/';     // remplacer par /
  4719.       a=fullpath+strlen(fullpath)-2;
  4720.       while( (*a!='/') && ( a > fullpath)) a--;
  4721.       if (*a=='/') a++;
  4722.       strcpybuff(pname,a);
  4723.       strncatbuff(path,fullpath,(int) (a - fullpath));
  4724.     }
  4725.   }
  4726. }
  4727.  
  4728.  
  4729.  
  4730. // -- Gestion protocole ftp --
  4731.  
  4732. #if HTS_WIN
  4733. int ftp_available(void) {
  4734.   return 1;
  4735. }
  4736. #else
  4737. int ftp_available(void) {
  4738.   return 1;   // ok!
  4739.   //return 0;   // SOUS UNIX, PROBLEMES
  4740. }
  4741. #endif
  4742.  
  4743.  
  4744. int hts_dgb_init = 0;
  4745. FILE* hts_dgb_init_fp = NULL;
  4746. static void hts_dgb(char* msg);
  4747. HTSEXT_API void hts_debug(int level) {
  4748.   hts_dgb_init = level;
  4749.   if (hts_dgb_init > 0) {
  4750.     hts_dgb("hts_debug() called");
  4751.   }
  4752. }
  4753. static void hts_dgb(char* msg) {
  4754.   if (hts_dgb_init > 0) {
  4755.     if (hts_dgb_init_fp == NULL) {
  4756. #ifdef _WIN32_WCE
  4757.       hts_dgb_init_fp = fopen("\\Temp\\hts-debug.txt", "wb");
  4758. #else
  4759.       hts_dgb_init_fp = fopen("hts-debug.txt", "wb");
  4760. #endif
  4761.       if (hts_dgb_init_fp != NULL) {
  4762.         fprintf(hts_dgb_init_fp, "* Creating file\r\n");
  4763.       }
  4764.     }
  4765.     if (hts_dgb_init_fp != NULL) {
  4766.       fprintf(hts_dgb_init_fp, "%s\r\n", msg);
  4767.       fflush(hts_dgb_init_fp);
  4768.     }
  4769.   }
  4770. }
  4771.  
  4772. HTSEXT_API int hts_init(void) {
  4773.   static int hts_init_ok = 0;
  4774.  
  4775.   hts_dgb("entering hts_init()");    /* debug */
  4776.  
  4777.   /* Ensure external modules are loaded */
  4778.   hts_dgb("calling htspe_init()");    /* debug */
  4779.   htspe_init();
  4780.  
  4781.   /* MD5 Auto-test */
  4782.   {
  4783.     char digest[32 + 2];
  4784.     unsigned char* atest = (unsigned char*)"MD5 Checksum Autotest";
  4785.     digest[0] = '\0';
  4786.     domd5mem(atest, strlen(atest), digest, 1); /* a42ec44369da07ace5ec1d660ba4a69a */
  4787.     if (strcmp(digest, "a42ec44369da07ace5ec1d660ba4a69a") != 0) {
  4788.       int fatal_broken_md5 = 0;
  4789.       assertf(fatal_broken_md5);
  4790.     }
  4791.   }
  4792.  
  4793.   hts_dgb("initializing default wrappers");    /* debug */
  4794.   if (!hts_init_ok) {
  4795.     hts_init_ok = 1;
  4796.     // default wrappers
  4797.     htswrap_init();
  4798.     htswrap_add("init",htsdefault_init);
  4799.     htswrap_add("free",htsdefault_uninit);
  4800.     htswrap_add("start",htsdefault_start);
  4801.     htswrap_add("change-options",htsdefault_chopt);
  4802.     htswrap_add("end",htsdefault_end);
  4803.     htswrap_add("check-html",htsdefault_checkhtml);
  4804.     htswrap_add("loop",htsdefault_loop);
  4805.     htswrap_add("query",htsdefault_query);
  4806.     htswrap_add("query2",htsdefault_query2);
  4807.     htswrap_add("query3",htsdefault_query3);
  4808.     htswrap_add("check-link",htsdefault_check);
  4809.     htswrap_add("pause",htsdefault_pause);
  4810.     htswrap_add("save-file",htsdefault_filesave);
  4811.     htswrap_add("link-detected",htsdefault_linkdetected);
  4812.     htswrap_add("transfer-status",htsdefault_xfrstatus);
  4813.     htswrap_add("save-name",htsdefault_savename);
  4814.     htswrap_add("send-header",htsdefault_sendheader);
  4815.     htswrap_add("receive-header",htsdefault_receiveheader);
  4816.   }
  4817.   
  4818.   hts_dgb("initializing SSL");    /* debug */
  4819. #if HTS_USEOPENSSL
  4820.   /*
  4821.   Initialize the OpensSSL library
  4822.   */
  4823.   if (!openssl_ctx && SSL_is_available) {
  4824.     if (SSL_load_error_strings) SSL_load_error_strings();
  4825.     SSL_library_init();
  4826.     ///if (SSL_load_error_strings)  SSL_load_error_strings();
  4827.     //if (ERR_load_crypto_strings) ERR_load_crypto_strings();
  4828.     // if (ERR_load_SSL_strings)    ERR_load_SSL_strings(); ???!!!
  4829.     // OpenSSL_add_all_algorithms();
  4830.     openssl_ctx = SSL_CTX_new(SSLv23_client_method());
  4831.     if (!openssl_ctx) {
  4832.       fprintf(stderr, "fatal: unable to initialize TLS: SSL_CTX_new(SSLv23_client_method)\n");
  4833.       abortLog("unable to initialize TLS: SSL_CTX_new(SSLv23_client_method)");
  4834.       assertf("unable to initialize TLS" == NULL);
  4835.     }
  4836.   }
  4837. #endif
  4838.   
  4839.   /* Init vars and thread-specific values */
  4840.   hts_dgb("initializing variables");    /* debug */
  4841.   hts_initvar();
  4842.   
  4843.   /* initialiser structcheck */
  4844.   // structcheck_init(1);
  4845.  
  4846.   hts_dgb("ending hts_init()");    /* debug */
  4847.   return 1;
  4848. }
  4849. HTSEXT_API int hts_uninit(void) {
  4850.   hts_cache_free(_hts_cache());
  4851.   hts_freevar();
  4852.   /* htswrap_free(); */
  4853.   return 1;
  4854. }
  4855.  
  4856. // defaut wrappers
  4857. void __cdecl htsdefault_init(void) {
  4858. }
  4859. void __cdecl htsdefault_uninit(void) {
  4860.   hts_freevar();
  4861. }
  4862. int __cdecl htsdefault_start(void* opt) {
  4863.   return 1; 
  4864. }
  4865. int __cdecl htsdefault_chopt(void* opt) {
  4866.   return 1;
  4867. }
  4868. int  __cdecl htsdefault_end(void) { 
  4869.   return 1; 
  4870. }
  4871. int __cdecl htsdefault_checkhtml(char* html,int len,char* url_adresse,char* url_fichier) {
  4872.   return 1;
  4873. }
  4874. int __cdecl htsdefault_loop(void* back,int back_max,int back_index,int lien_n,int lien_tot,int stat_time,hts_stat_struct* stats) {    // appelΘ α chaque boucle de HTTrack
  4875.   return 1;
  4876. }
  4877. char* __cdecl htsdefault_query(char* question) {
  4878.   return "";
  4879. }
  4880. char* __cdecl htsdefault_query2(char* question) {
  4881.   return "";
  4882. }
  4883. char* __cdecl htsdefault_query3(char* question) {
  4884.   return "";
  4885. }
  4886. int __cdecl htsdefault_check(char* adr,char* fil,int status) {
  4887.   return -1;
  4888. }
  4889. void __cdecl htsdefault_pause(char* lockfile) {
  4890.   while (fexist(lockfile)) {
  4891.     Sleep(1000);
  4892.   }
  4893. }
  4894. void __cdecl htsdefault_filesave(char* file) {
  4895. }
  4896. int __cdecl htsdefault_linkdetected(char* link) {
  4897.   return 1;
  4898. }
  4899. int __cdecl htsdefault_xfrstatus(void* back) {
  4900.   return 1;
  4901. }
  4902. int __cdecl htsdefault_savename(char* adr_complete,char* fil_complete,char* referer_adr,char* referer_fil,char* save) {
  4903.   return 1;
  4904. }
  4905. int __cdecl htsdefault_sendheader(char* buff, char* adr, char* fil, char* referer_adr, char* referer_fil, htsblk* outgoing) {
  4906.   return 1;
  4907. }
  4908. int __cdecl htsdefault_receiveheader(char* buff, char* adr, char* fil, char* referer_adr, char* referer_fil, htsblk* incoming) {
  4909.   return 1;
  4910. }
  4911. // end defaut wrappers
  4912.  
  4913.  
  4914.  
  4915. // Fin
  4916.  
  4917.